如何将函数的默认值添加到 Sailsjs 中的模型 [英] How to add a default value from a function to the model in Sailsjs
问题描述
这是我的模型
module.exports = {
attributes: {
ip: {
type: 'ip'
},
useragent: {
type: 'text'
},
type: 'int'
}
}
};
所以我需要的是在创建记录之前我需要从传入的请求中自动填充 ip 和用户代理
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
这可行吗?
谢谢
推荐答案
您可以通过 Sails policy 通过在 req.options
上设置一些属性.如果您有一个 User
模型并且正在使用蓝图 create
路由,那么在您的 config/policies 中,您将拥有:
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'
}
在 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();
};
我不记得获取用户 IP 的首选方式,但是 这个问题 看起来很有希望.对于用户代理,您可以尝试 req.headers['user-agent']
.
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']
.
如果您使用的是自定义控制器操作而不是蓝图,这仍然可以正常工作,您只需要将随请求传递的值与 req.options.values
合并.
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
.
这篇关于如何将函数的默认值添加到 Sailsjs 中的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!