Or Weinberger
Or Weinberger

Reputation: 7482

Call controller on afterCreate

I have the following code for my Sessions model:

module.exports = {

  attributes: {

  },
  afterCreate: function(value,next) {
    next();
  }

};

And the following Sessions Controller:

module.exports = {

  saveSession: function(res,req) {
    console.log('in save');
  }
};

I want to save a value to a user's session afterCreate

How can I call the saveSession function from my model? I tried Sessions.saveSession() but it doesn't work.

Upvotes: 1

Views: 916

Answers (2)

I think that you want to save a value to a cookie or create another database record am i correct?

If so, you dont need to call a controller action from the model (not recommended), you just need to create a new record or save the value to the cookie, here are some alternatives that i see possible in your scenario.

creating another record:

    // on models/YourModel
    module.exports = {

      attributes: {

      },
      afterCreate: function(newlyInsertedRecord,next) {
          ModelOrResource.create({
              param1: newlyInsertedRecord.attributeYouWant,
              param2: value2
              // and so on
          }).exec(function(err, recordCreated){
              if(err) return next(err);
              // do somethign with recordCreated if you need to
              // ...
              next();
          })

      }

    };

Saving a value to a cookie:

    module.exports = {

        attributes: {

        },
        afterCreate: function(newlyInsertedRecord, next) {
            // do some other stuff not related to calling a controller action ;)
            next();
        }

    };

This code was retrived from snippets from my own projects, so it should work on sails 0.9.x

Hope it helps!

Upvotes: 0

JohnGalt
JohnGalt

Reputation: 2881

I don't think you need a session model and it's not a good idea to call a controller method directly.

I'd recommend just set req.session when you're trying to save the session and it'll be auto-saved when you respond from that controller action.

afterCreate will never have access to req unless you pass it down which I wouldn't recommend.

The pattern is something like:

{
  // …
  login: function (req,res) {
  User.findOne({
    username: req.param('username'),
    password: req.param('password')
  }).exec(function (err, user) {
    if (err) return res.serverError(err);
    if (!user) return res.view('/login');
    req.session.user = user.toJSON();
    return res.redirect('/dashboard');
  });
}
  // ...

Upvotes: 1

Related Questions