Search code examples
node.jsexpresssails.jssails-mongo

SAILS JS 1.0 model callback lifecycle is not called


well, I'm trying to create a user with Sails 1.0.0-42, the problem is that the callback lifecycle of the user model is not called. I have tried in many ways and nothing is called. Thanks in advance.

this is the code of Action2 "signup":

module.exports = {

   friendlyName: 'Create User',

   description: 'user create action2',

   inputs: {

        name: {
            description: 'user create',
            type: 'string',
            required: true
        },
        email: {
            description: 'user create',
            type: 'string',
            required: true
        },
        password: {
            description: 'user create',
            type: 'string',
            required: true
        },

   },

   exits: {
      notFound: {
        description: 'ERRO create user.',
        responseType: 'notFound'
      }
   },

   fn: async function (inputs, exits) {

        const {name, email, password} = inputs;

        var user = await User.create({name, email, password}).fetch();

        if(!user) return exits.notFound();

        return exits.success(user);

   }
};

this is the user model code

    var bcrypt = require('bcrypt');

module.export = {

    attributes: {

        name: {
            type: 'string',
            required: true,
        },

        email: {
            type: 'string',
            required: true,
        },

        password: {
            type: 'string',
            minLength: 6,
            required: true,
            columnName: 'hashed_password'
        },

    },

    // Lifecycle Callbacks

    beforeCreate: function (values, cb) {

        // Hash password
        bcrypt.hash(values.password, 10, function(err, hash) {
            if(err) return cb(err);
            values.password = hash;
            cb();
        });
    }

};

the user is created, but the password is not encrypted, and in the tests the beforeCreate is not called.


Solution

  • Your model file declares:

    module.export
    

    But it needs to be:

    module.exports
    

    That s makes a big difference!

    The reason it works at all with your current code is that, by default, the built-in sails-disk database is schemaless, so even though your User.js file wasn't exporting anything, it still lets you create records with whatever fields you want.