是否可以直接在SailsJS中的Model中访问会话变量 [英] Is it possible to access a session variable directly in a Model in SailsJS
问题描述
URL:
/ api / myModel / create [post]
型号:
module.exports = {
适配器:'mongo',
schema:true,
属性:{
user:{
model:'user',
required:true,
index:true
},
item:{
model:'item',
required:true,
index:true
},
数量:{
必需: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){
/ *我想自动设置登录
USERID here * /
next();
}
};
我想在字段中自动设置登录的用户会话userid的值。我必须创建自己的自定义路由/控制器操作才能正确访问req字段?
它与 sails.js重复使用模型中的会话参数,所以答案是不。但是你有几个选择。您可以在策略中设置此值,也可以重写蓝图操作。我还要求会话用户附加到所有模型,并以这种方式执行。
例如,在策略中,这将在任何蓝图上创建一个userId创建动作
req.query.userId = req.session.userId;
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?
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;
这篇关于是否可以直接在SailsJS中的Model中访问会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!