【发布时间】:2017-08-19 22:37:09
【问题描述】:
我正在使用NodeJS 和sequelize。我的应用程序中有两种登录方式。一种是普通用户登录,一种是公司登录。
下面的代码首先在 company 表中查找 token,如果不存在则移动到 user 表中查找。
这样我就知道谁登录了系统。
有没有更好的方法?
或
有没有一种方法可以让我同时在两个表中搜索,而不是等待sequelize 在一个表中搜索然后再执行另一个?
var token = req.get('Auth') || '';
db.token.findOne({
where:{
tokenHash: cryptojs.MD5(token).toString()
}
}).then(function(tokenInstance){
if(!tokenInstance){
throw new Error();
}
req.token = tokenInstance;
return db.company_auth.findByToken(token); //looks in the first table (company)
}).then(function(entity){
if(entity === null){
return db.user.findByToken(token); //if not found (then looks in the second table - user)
}else{
req.entity = entity;
next();
}
}).then(function(user){
req.user = user;
next();
}).catch(function(e){
console.log(e);
res.status(401).send();
});
TIA!
【问题讨论】:
-
是的,你可以....有
-
您的代码当前调用了两次
next()。我不认为这是故意的? -
@Bergi 这实际上是有意的,因为如果在 company 表中找到令牌,它将继续执行其他操作,而不是在 user 表中搜索。
-
@Beginner:如果你能解释一下如何?
-
@RahulArora 我不是这个意思。请参阅我正在复制行为的答案。
标签: javascript node.js promise sequelize.js