0

this is my model

module.exports = {

    attributes: {

        ip: {
            type: 'ip'
        },
        useragent: {
            type: 'text'
        },
        type: 'int'
        }
    }
};

So what I need is before the record is created I need the ip and the useragent to be filled automatically from the request that comes in

Is this feasible ?

Thank you

Sahan
  • 1,422
  • 2
  • 18
  • 33

2 Answers2

1

You can do this via a Sails policy by setting some properties on req.options. If you have a User model and are using the blueprint create route, then in your config/policies you'd have:

UserController: {
  create: 'setValues'
}

and in api/policies/setValues.js:

module.exports = function(req, res, next) {

  req.options.values = req.options.values || {};
  req.options.values.ip = <SET IP>;
  req.options.values.agent = <SET USER AGENT>;
  return next();

};

I don't remember the preferred way to get user IP, but this question looks promising. For user agent you can try req.headers['user-agent'].

If you're using a custom controller action rather than the blueprints, this will still work fine, you'll just need to merge the values passed with the request with req.options.values.

Community
  • 1
  • 1
sgress454
  • 24,870
  • 4
  • 74
  • 92
0

Yes you could do this with Lifecyclecallbacks (see: http://sailsjs.org/#/documentation/concepts/ORM/Lifecyclecallbacks.html)

module.exports = {
 attributes: {
  ip: {
   type: 'ip'
  },
  useragent: {
   type: 'text'
  },

 },

 // Lifecycle Callbacks
 beforeCreate: function (values, cb) {
  values.ip = <SET IP>
  values.useragent = <SET USER AGENT>
  cb();
 });
};
mdunisch
  • 3,627
  • 5
  • 25
  • 41
  • I specifically said "I need to get the values from the REQUEST. I do not want to fill the values manually – Sahan Sep 25 '14 at 12:01