How to add a default value from a function to the model in Sailsjs

人盡茶涼 提交于 2019-12-13 03:17:39

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!