问题
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
回答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
.
回答2:
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();
});
};
来源:https://stackoverflow.com/questions/26029948/how-to-add-a-default-value-from-a-function-to-the-model-in-sailsjs