tgriesser / checkit

simple, flexible validations for node and the browser
MIT License
223 stars 53 forks source link

Using context correctly #62

Closed chamini2 closed 8 years ago

chamini2 commented 8 years ago

Hi, I checked the example in #19 to use context (for transacting) and I replicated the same idea in code and can't get the context var to work keep the information.

const createRules = {
  status: 
    [ 'required'
    , function (val) {
        if (! _.includes(statusArray, val)) {
          throw new Error('400:status:Invalid status')
        }
      } 
    ],

  commission: 
    [ 'required'
    , 'between:0:1'
    ],

  activity_request_id: { 
      rule: function (val, params, context) {
        console.log("params: ", params)
        console.log("context: ", context, context && context.transacting)
        return ActivityRequest.where({id: val}).fetch()
          .then((actReq) => {
            if (actReq === null) {
              // no ActivityRequest
              throw new Error('404:The order has to be related to an existent activity request')
            } else if (actReq.attributes.status !== 'approved') {
              // ActivityRequest not approved
              throw new Error('400:Activity request must be approved to create order')
            }
          })
      }
    }
  }
};

var Order = bookshelf.Model.extend({
  tableName: 'orders',
  hasTimestamps: true,

  activityRequest: function() {
    return this.belongsTo('ActivityRequest');
  },
  bill: function() {
    return this.belongsTo('Bill');
  },
  wireTransactionResponses: function() {
    return this.hasMany('WireTransactionResponses');
  },
  paymentGatewayResponses: function() {
    return this.hasMany('PaymentGatewayResponses');
  },

  initialize : function(){    
    this.on("creating", function(model, attrs, options){
      // generate uuid (Universally Unique IDentifier)
      model.attributes.reference_code = uuid.v4();    

      // if no status was given, set pending
      model.attributes.status = model.attributes.status || 'pending';

      model._validateCreate(model, attrs, options)
    })
  },

  _validateCreate : function(model, attrs, options) {
    console.log('attrs:', attrs)
    console.log('options:', options)
    return checkit(createRules, {context: options})
      .run(this.attributes)
      .catch(checkit.Error, (err) => {
        console.log(err);
        throw errors.toBoom(err); 
      }); 
  }

});

The console.log('options:', options) does print a {transacting: ... }, but console.log("context: ", context, context && context.transacting) prints {} undefined.

chamini2 commented 8 years ago

I figured it out, I had to pass the context in the second argument of run (.run(this.attributes, options)).