Is it possible to access a session variable directly in a Model in SailsJS

倾然丶 夕夏残阳落幕 提交于 2019-12-31 05:44:26

问题


I have a situation where I'd like to use Sails' create blueprint on a Model. However, I need to access a session variable on that create:

URL: /api/myModel/create [post]

Model: module.exports = {

    adapter: 'mongo',
    schema: true,
    attributes: {
        user: {
            model:'user',
            required:true,
            index:true
        },
        item: {
            model:'item',
            required:true,
            index:true
        },
        quantity: {
            required:true,
            type: 'integer',
            defaultsTo: 1,
            min: 0
        },
        size: {
            required:true,
            type:'string'
        },
        container: {
            required:true,
            type:'string'
        },
        dateManuf: {
            required:true,
            date:true
        }
    },
    beforeValidation:function(values, next) {
        /* I want to automatically set the logged in 
           USERID here */

        next();
    }
};

I want to automatically set the value of the logged in user session userid in the field. Do I have to create my own custom route/controller action to do that to properly have access to the "req" field?


回答1:


It is a duplicate of sails.js Use session param in model, so the answer is no. However you have a few options. You can set this value in policies, or you can rewrite blueprint actions to do this. I also require the session user to attach to all models and do it this way.

For instance this in a policy will set a userId on any blueprint create action

req.query.userId = req.session.userId; 


来源:https://stackoverflow.com/questions/24457552/is-it-possible-to-access-a-session-variable-directly-in-a-model-in-sailsjs

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