Kuba
Kuba

Reputation: 2089

Waterline Lifecycle Callbacks not get invoked

I'm currently running Sails.js v. 0.11.0 and Waterline v. 0.10.0b.

I have a user model with two lifecycle callbacks that do not get invoked when I destroy the user. I tried user.destroy() as well as User.destroy(id). Should I explicitly call those afterDestroy callbacks somehow, or should I activate them with a setting somewhere? My database is MySQL via sails-mysql. Any help would be very appreciated!

User Model

module.exports = {
  tableName: 'user',
  attributes: {
    name: {
      type: 'string',
      required: true
    },
    lastName: {
      type: 'string',
      required: true
    },

    ...

    beforeDestroy: function(destroyedRecord, next) {
      console.log('!!!!!destroyedRecord', destroyedRecord);
      next();
    },

    afterDestroy: function(destroyedRecord, next) {
      console.log('!!!!!destroyedRecord', destroyedRecord);
      next();
    },

    toJSON: function () {
      var obj = this.toObject();
      delete obj.password;
      return obj;
    }
  },

  getFullName: function (user) {
    return user.name + ' ' + user.lastName;
  }

};

Remove Function

remove: function (req, res, next) {

  var id = req.param('id');

  User.findOne({'id' : id}).then(function(user){
      user.destroy();
      res.send(200);
  }).catch(function(err){
      console.log(err);
      res.send(400);
  });

Upvotes: 0

Views: 353

Answers (1)

Meeker
Meeker

Reputation: 5979

Callbacks are outside of attributes and on a side note you can put fullname inside attributes as shown below.

module.exports = {
  tableName: 'user',
  attributes: {
    name: {
      type: 'string',
      required: true
    },
    lastName: {
      type: 'string',
      required: true
    },

    fullName: function () {
      return this.name + ' ' + this.lastName;
    }


  },

  beforeDestroy: function(destroyedRecord, next) {
    console.log('!!!!!destroyedRecord', destroyedRecord);
    next();
  },

  afterDestroy: function(destroyedRecord, next) {
    console.log('!!!!!destroyedRecord', destroyedRecord);
    next();
  },

  toJSON: function () {
    var obj = this.toObject();
    delete obj.password;
    return obj;
  }

};

Upvotes: 2

Related Questions