Example #1
0
      _processFail: function(t, secret) {
        var that = this;

        console.log("_processFail...");
        console.log(secret);
        return Promise.bind({})
        .then(function() {
          return Promise.cast(that.find({where: {secret: secret, status: STATUS_PROCESSING}, transaction: t})).bind(this).then(checkExist)
        }).then(function() {
          return Promise.cast(that.update({status: STATUS_PROCESS_FAIL}, {where: {secret: secret, status: STATUS_PROCESSING}, transaction: t}));
        });
      },
Example #2
0
 _execute: BluebirdPromise.method(function(client, sql, args) {
   return BluebirdPromise.bind({})
   .then(function() {
     return client.queryAsync(sql, args);
   })
   .then(function(result) {
     return {
       rows: result.rows,
       fields: _.map(result.fields, 'name')
     };
   });
 })
Example #3
0
Client.prototype.createNewPayment = function (address, amount, memo) {
    if (!UInt160.is_valid(address)) {
        throw new Error("Address must be a valid Stellar address");
    }
    return Promise.bind(this)
        .then(function () {
            return validateAmount(amount);
        })
        .then(function () {
            return this.database.insertNewTransaction(address, amount, memo);
        });
};
Example #4
0
      'deploy:deploy': () => BbPromise.bind(this)
        .then(this.setBucketName)
        .then(this.cleanupS3Bucket)
        .then(this.uploadArtifacts)
        .then(this.updateStack)
        .then(() => {
          const msg = this.options.noDeploy ?
            'Did not deploy due to --noDeploy' :
            'Deployment successful!';

          this.serverless.cli.log(msg);
        }),
Example #5
0
 this.load = function(app) {
     this.app = app;
     return bluebird.bind(this).then(function() {
         return fs.readFileAsync(fspath.join(this.app.path, 'manifest.json'));
     }).then(function(data) {
         this.manifest = JSON.parse(data);
         for (var p in this.manifest) {
             copy(this.manifest[p], this[p]);
         }
         $rootScope.$apply();
     });
 };
Example #6
0
 _execute: BluebirdPromise.method(function(connection, sql, args, returning) {
   return BluebirdPromise.bind({})
   .then(function() {
     return connection.queryAsync(sql, args);
   })
   .spread(function(rows, fields) {
     if (rows.insertId) { returning(rows.insertId); }
     return {
       rows: fields ? rows : [],
       fields: _.map(fields, 'name')
     };
   });
 })
 const after = () => {
   if (!isFunctionRuntimePython(arguments)) {
     return;
   }
   return BbPromise.bind(this)
     .then(removeVendorHelper)
     .then(() =>
       injectAllRequirements.bind(this)(
         arguments[1].functionObj &&
           arguments[1].functionObj.package.artifact
       )
     );
 };
Example #8
0
 this.delete = function(cls, name) {
     return bluebird.bind(this).then(function() {
         this.temp = _.cloneDeep(this.manifest);
         var index = _.findIndex(this.temp[cls], 'name', name);
         this.temp[cls].splice(index, 1);
         var data = JSON.stringify(this.temp, null, 2);
         return fs.writeFileAsync(fspath.join(this.app.path, 'manifest.json'), data);
     }).then(function() {
         this.manifest = this.temp;
         this.temp = null;
         $rootScope.$apply();
     });
 };
Example #9
0
 getFilter: function (scope) {
   return Promise
     .bind(this)
     .then(function () {
       return this.buildConditions(scope);
     })
     .then(function (conditions) {
       var defaultFilter = this.defaultFilter ? this.defaultFilter : {};
       var queryFilter = scope.req.query.filter;
       var filter = _.assign((queryFilter ? JSON.parse(queryFilter) : defaultFilter), conditions);
       return filter;
     });
 },
Example #10
0
    test('Getting fresh stats after a deletion', function () {
      var responses = fixtures.makeResponses(5);
      var url = BASEURL + '/surveys/' + this.surveyId + '/responses';

      return Promise.bind(this)
      .then(function () {
        // Add some responses.
        return request.postAsync({
          url: url,
          json: responses
        });
      }).spread(function (response, body) {
        response.statusCode.should.equal(201);

        this.responseId = body.responses[0].id;

        // Get the stats
        return request.getAsync({
          url: BASEURL + '/surveys/' + this.surveyId + '/stats',
          jar: false
        });
      }).spread(function (response, body) {
        response.statusCode.should.equal(200);

        response = JSON.parse(body);
        this.stats1 = response.stats;

        // Delete a response
        return request.delAsync({
          url: BASEURL +
               '/surveys/' + this.surveyId +
               '/responses/' + this.responseId,
          jar: this.userAJar,
        });
      }).spread(function (response, body) {
        response.statusCode.should.equal(204);

        // Get the stats again
        return request.getAsync({
          url: BASEURL + '/surveys/' + this.surveyId + '/stats',
          jar: false
        });
      }).spread(function (response, body) {
        response.statusCode.should.equal(200);

        response = JSON.parse(body);
        this.stats2 = response.stats;

        assert.notDeepEqual(this.stats2, this.stats1);
      });
    });
Example #11
0
    test('Getting cached stats for a survey within a bounding box', function () {
      var polygon = {
        type: 'Polygon',
        coordinates: [[
          [-122.55523681640625,37.67077737288316],
          [-122.55523681640625,37.83690319650768],
          [-122.32040405273438,37.83690319650768],
          [-122.32040405273438,37.67077737288316],
          [-122.55523681640625,37.67077737288316]
        ]]
      };
      var polygonString = encodeURIComponent(JSON.stringify(polygon));
      var responses = fixtures.makeResponses(5);
      var url = BASEURL + '/surveys/' + this.surveyId + '/responses';

      return Promise.bind(this)
      .then(function () {
        // Add some responses.
        return request.postAsync({
          url: url,
          json: responses
        });
      }).spread(function (response, body) {
        response.statusCode.should.equal(201);

        // Get the stats
        return request.getAsync({
          url: BASEURL + '/surveys/' + this.surveyId + '/stats?intersects=' + polygonString,
          jar: false
        });
      }).spread(function (response, body) {
        response.statusCode.should.equal(200);

        response = JSON.parse(body);
        this.stats1 = response.stats;

        // Get the stats again
        return request.getAsync({
          url: BASEURL + '/surveys/' + this.surveyId + '/stats?intersects=' + polygonString,
          jar: false
        });
      }).spread(function (response, body) {
        response.statusCode.should.equal(200);

        response = JSON.parse(body);
        this.stats2 = response.stats;

        assert.deepEqual(this.stats2, this.stats1);
      });
    });
Example #12
0
    test('Getting fresh stats after an addition', function () {
      var responses = fixtures.makeResponses(5);
      var url = BASEURL + '/surveys/' + this.surveyId + '/responses';

      return Promise.bind(this)
      .then(function () {
        // Add some responses.
        return request.postAsync({
          url: url,
          json: responses
        });
      }).spread(function (response, body) {
        response.statusCode.should.equal(201);

        // Get the stats
        return request.getAsync({
          url: BASEURL + '/surveys/' + this.surveyId + '/stats',
          jar: false
        });
      }).spread(function (response, body) {
        response.statusCode.should.equal(200);

        response = JSON.parse(body);
        this.stats1 = response.stats;

        var newResponses = fixtures.makeResponses(2, {
          parcelBase: 4444
        });
        // Add some more responses.
        return request.postAsync({
          url: url,
          json: newResponses
        });
      }).spread(function (response, body) {
        response.statusCode.should.equal(201);

        // Get the stats again
        return request.getAsync({
          url: BASEURL + '/surveys/' + this.surveyId + '/stats',
          jar: false
        });
      }).spread(function (response, body) {
        response.statusCode.should.equal(200);

        response = JSON.parse(body);
        this.stats2 = response.stats;

        assert.notDeepEqual(this.stats2, this.stats1);
      });
    });
Example #13
0
 'aws:deploy:finalize:cleanup': () => BbPromise.bind(this)
   .then(() => {
     if (this.options.noDeploy || this.serverless.service.provider.shouldNotDeploy) {
       return BbPromise.resolve();
     }
     return this.cleanupS3Bucket();
   })
   .then(() => {
     if (this.options.package || this.serverless.service.package.path) {
       return BbPromise.bind(this)
         .then(() => this.serverless.pluginManager.spawn('aws:common:cleanupTempDir'));
     }
     return BbPromise.resolve();
   }),
    self.tradeCheckLooper = function(finishedResponse){
        if(finishedResponse){
            return finishedResponse;
        }

        console.log('order ', this.id, 'is still running, iteration', this.retries++);

        // keep looping this baby
        if(this.retries <= 1){
            return Promise.bind(this).then(self.tradeChecker); // first retry do immediately
        } else {
            return Promise.delay(self.pollingInterval).bind(this).then(self.tradeChecker);
        }
    };
Example #15
0
      edit: function(id, d) {
        var that = this;

        if (!d) {
          return Promise.reject(new Error("not valid info"));
        }
        if (d.price) {
          return Promise.reject(new Error("you cannot update the price. for some reason"));
        }
        if (d.subtract || d.subtract !== undefined) {
          return Promise.reject(new Error("you cannot update the subtract. for some reason"));
        }

        d = _.pick(d, "name", "name_en", "description", "description_en", "image", "state");
        // d = _.pick(d, "zids", "sids", "cids", "name", "name_en", "description", "description_en", "image");
        // var image = d.image;
        d.date_modified = Date.now();

        if (d.name !==undefined && !d.name) {
          return Promise.reject(new Error("You need to specify a name for the product"));
        }
        if (d.state !==undefined && [STATE_ENABLED, STATE_DISABLED].indexOf(d.state) === -1) {
          return Promise.reject(new Error("state can be disabled or enabled only"));
        }
        if (d.description !==undefined && !d.description) {
          return Promise.reject(new Error("You need to specify a description for the product"));
        }
        // if (d.zids !==undefined && !d.zids || !d.zids.length) {
        //   return Promise.reject(new Error("You need to specify a zids for the product"));
        // }
        // if (d.price !== undefined && (!d.price || d.price <= 0)) {
        //   return Promise.reject(new Error("You need to specify a price for the product....."));
        // }

        if (!id || !validator.isInt(id.toString())) {
          return Promise.reject(new Error("this product does not exist"));
        }

        return Promise.bind({})
        .then(function() {
          return that.load(id).bind(this).then(checkProductExist)
        }).then(function() {
          return Promise.cast(that.update(d, {where: {id: id}}))
        }).then(function() {
          // if (image) return that.setAvatar(id, image);
        }).then(function() {
          return that.load(id);
        });
      }
Example #16
0
 execute: BluebirdPromise.method(function(sql, args, options) {
   var self = this;
   var opts = options || {};
   return BluebirdPromise.bind({}).then(function() {
     return opts.client ||
       (this.acquired = true, self.pool.acquireAsync());
   })
   .then(function(client) { this.client = client; })
   .then(function() {
     return self._execute(this.client, sql, args);
   })
   .finally(function() {
     return this.acquired && self.pool.release(this.client);
   });
 }),
Example #17
0
File: index.js Project: gwicke/preq
Request.prototype.retry = function (err) {
    if (this.retries) {
        this.retries--;
        // exponential backoff with some fuzz, but start with a short delay
        this.delay = this.delay * 2 + this.delay * Math.random();
        // grow the timeout linearly, plus some fuzz
        this.timeout += this.options.timeout + Math.random() * this.options.timeout;

        return P.bind(this)
        .delay(this.delay)
        .then(this.run);
    } else {
        throw err;
    }
};
Example #18
0
          .catch(e => {
            if (e.message.indexOf('does not exist') > -1) {
              if (this.serverless.service.provider.deploymentBucket) {
                this.createLater = true;
              }

              if (this.options.noDeploy || this.createLater) {
                return BbPromise.resolve();
              }
              return BbPromise.bind(this)
                .then(this.create);
            }

            throw new this.serverless.classes.Error(e);
          })
Example #19
0
Submitter.prototype.submitTransactions = function () {
    return Promise.bind(this)
        .then(function () {
            return this.database.getSignedUnconfirmedTransactions();
        })
        .each(function (transaction) {
            return this.submitTransaction(transaction);
        })
        // presequence errors resolve themselves once txns with a lower seq number have been confirmed
        .catch(Submitter.errors.PreSequenceError, function (err) {
            this.log.error("PreSequenceError", err);
        })
        // TODO: remove when tx rpc call is fixed to always include a meta tag
        .catch(Submitter.errors.NoMetaTransactionError, function () {});
};
Example #20
0
      'rollback:rollback': () => {
        if (!this.options.timestamp) {
          const command = this.serverless.pluginManager.spawn('deploy:list');
          this.serverless.cli.log([
            'Use a timestamp from the deploy list below to rollback to a specific version.',
            'Run `sls rollback -t YourTimeStampHere`',
          ].join('\n'));
          return command;
        }

        return BbPromise.bind(this)
          .then(this.setBucketName)
          .then(this.setStackToUpdate)
          .then(this.updateStack);
      },
Example #21
0
 return function(req, res, next) {
   var request = new Request(req);
   var response = new Response(res);
   return Promise.bind(that)
     .then(function() {
       return this.server.authenticate(request, response, options);
     })
     .tap(function(token) {
       res.locals.oauth = { token: token };
       next();
     })
     .catch(function(e) {
       return handleError.call(this, e, req, res, null, next);
     });
 };
Example #22
0
Payments.prototype.handleFatalError = function (err) {
    // uncaugt exception, fatal error
    this.log.error("Fatal error", err);
    this.fatalError = err;
    return Promise.bind(this)
        .then(function () {
            // if this fatal error has a transaction, mark error as fatal
            if (err.transaction) {
                return this.database.markTransactionError(err.transaction, err.name, true);
            }
        })
        .then(function () {
            return Promise.reject(err);
        });
};
Example #23
0
 .then(plugins => {
   const plugin = plugins.find((item) => item.name === this.options.pluginName);
   if (plugin) {
     return BbPromise.bind(this)
     .then(this.uninstallPeerDependencies)
     .then(this.pluginUninstall)
     .then(this.removePluginFromServerlessFile)
     .then(() => {
       this.serverless.cli.log(`Successfully uninstalled "${this.options.pluginName}"`);
       return BbPromise.resolve();
     });
   }
   const message = `Plugin "${this.options.pluginName}" not found. Did you spell it correct?`;
   throw new this.serverless.classes.Error(message);
 });
Example #24
0
  return function(req, res, next) {
    var request = new Request(req);

    return Promise.bind(this)
      .then(function() {
        return server.authenticate(request);
      })
      .tap(function(token) {
        req.app.locals.oauth = { token: token };
      })
      .catch(function(e) {
        return handleError(e, req, res);
      })
      .finally(next);
  };
AuthenticateHandler.prototype.handle = function(request, response) {
  if (!(request instanceof Request)) {
    throw new InvalidArgumentError('Invalid argument: `request` must be an instance of Request');
  }

  if (!(response instanceof Response)) {
    throw new InvalidArgumentError('Invalid argument: `response` must be an instance of Response');
  }

  // Extend model object with request
  this.model.request = request;

  return Promise.bind(this)
    .then(function() {
      return this.getTokenFromRequest(request);
    })
    .then(function(token) {
      return this.getAccessToken(token);
    })
    .tap(function(token) {
      return this.validateAccessToken(token);
    })
    .tap(function(token) {
      if (!this.scope) {
        return;
      }

      return this.verifyScope(token);
    })
    .tap(function(token) {
      return this.updateResponse(response, token);
    })
    .catch(function(e) {
      // Include the "WWW-Authenticate" response header field if the client
      // lacks any authentication information.
      //
      // @see https://tools.ietf.org/html/rfc6750#section-3.1
      if (e instanceof UnauthorizedRequestError) {
        response.set('WWW-Authenticate', 'Bearer realm="Service"');
      }

      if (!(e instanceof OAuthError)) {
        throw new ServerError(e);
      }

      throw e;
    });
};
Example #26
0
  select: function (scope) {
    var limit;
    var page;

    return Promise
      .bind(this)
      .then(this.pre.bind(this, scope))
      .then(this.buildConditions.bind(this, scope))
      .then(this.getFilter.bind(this, scope))
      .then(function(filter) {
        // field list
        var fieldList = this.extractFieldList(scope);
        // q
        var q = scope.req.query.q;
        // orderBy
        var orderBy = this.getOrderBy(scope);
        // limit
        var limit = this.getLimit(this.config.defaultPerPage, this.config.maxPerPage, scope);
        // page
        page = this.getPage(scope);

        return this.dataSource.find({
          filter: filter,
          fields: fieldList,
          q: q,
          qFields: this.qFields,
          sort: orderBy,
          limit: limit,
          skip: (page - 1) * limit,
          queryPipe: this.queryPipe ? _.bind(function (query) {
            this.queryPipe(query, scope);
          }, this) : undefined
        });
      })
      .then(function (collection) {
        return this.collectionPost(collection, scope);
      })
      .then(function (collection) {
        var _this = this;
        return Promise.map(collection, function (item) {
          return _this.post(item, scope);
        });
      })
      .then(function (collection) {
        this.addLinkHeaders(page, limit, collection.length, scope);
        return collection;
      });
  },
Example #27
0
Submitter.prototype.submitTransaction = function (transaction) {
    return Promise.bind(this)
        .then(function () {
            return this.network.submitTransactionBlob(transaction.txblob);
        })
        .then(function (response) {
            return this._processSubmitResponse(response);
        })
        .then(function () {
            return this.database.markTransactionSubmitted(transaction);
        })
        .catch(function (err) {
            err.transaction = transaction;
            return this._handleSubmitError(err, transaction);
        });
};
  getReleaseTag: function(repo) {
    return Promise.bind(this)
      .then(function() {

        //return if already cached
        if(this.releaseTag){
          return this.releaseTag;
        }

        return this.getSortedTags(repo)
          .then(function(tags) {
            this.releaseTag = _.first(tags);
            return this.releaseTag;
          }.bind(this));
      });
  },
Example #29
0
 it('supports `notNull`', function(done) {
   var table = 'azul_not_null';
   BluebirdPromise.bind(this)
   .then(function() {
     return db.schema.createTable(table, function(table) {
       table.string('column').notNull();
     });
   })
   .then(function() { return db.insert(table, { column: null }); })
   .throw(new Error('Expected insert error to occur.'))
   .catch(function(e) {
     expect(e.message).to.match(/(cannot|violates|constraint).*null/i);
   })
   .finally(function() { return db.schema.dropTable(table).ifExists(); })
   .done(function() { done(); }, done);
 });
Example #30
0
    .reduce(function(previous, z) {
      var sourceVrt = previous[0],
          sourceCoords = previous[1];

      return Promise
        .bind(this)
        .then(function() {
          return tile.call(this, sourceVrt, z, sourceCoords, options);
        })
        .then(function(resultVrt) {
          var resultCoords = _.map(sourceCoords, function(coord) {
            return [(coord[0] / 2) | 0, (coord[1] / 2) | 0];
          });
          return [resultVrt, CoordSet(resultCoords).toArray()];
        });
    }, [initialVrt, initialCoords]);