Sailsjs/Waterline : Is there a way to catch lifecycle events on associations?

401 Views Asked by At

I would like to be able to catch add/remove events on associations (server side) because I need to process a function each time a element is added to or removed from a collection. Is it possible ?

1

There are 1 best solutions below

2
On

You can use the before/after/Update/Create/Validate on the collection being updated.

here is an example where an order has a course (Many To One). I check if the course was updated (kinda hacky but sails has a pull request currently to check for updated data) and if so, then I perform some actions against the association

// Order.js
  beforeUpdate : function(values, cb){

    if(values.course) {
      Order.findOne(values.id)
        .exec(function(err, originalOrder){
          if(originalOrder.course != values.course)

            Course.updateEnrolled(values.course, function(err){

              if(err) console.log(err);

            });

            Course.updateEnrolled(originalOrder.course, function(err){

              if(err) console.log(err);

            });

            Student.sendCourseEmail(values.student,values.course, function(){
              // no call back, console error generated form method
            });


        });

    }

    return cb();

  },