【问题标题】:Sequelize better way of writing this codeSequelize 编写此代码的更好方法
【发布时间】:2017-08-19 22:37:09
【问题描述】:

我正在使用NodeJSsequelize。我的应用程序中有两种登录方式。一种是普通用户登录,一种是公司登录。

下面的代码首先在 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


【解决方案1】:

是的,您可以轻松地同时在两个表中搜索并使用Promise.all 等待两个结果:

db.token.findOne({
    where:{
        tokenHash: cryptojs.MD5(req.get('Auth') || '').toString()
    }
}).then(function(tokenInstance){
    if (!tokenInstance)
        throw new Error("found no token");

    req.token = tokenInstance;
    return Promise.all([
        db.company_auth.findByToken(token), //looks in the first table (company)
        db.user.findByToken(token) // also looks in the second table - user)
    ]);
}).then(function([entity, user]){
    if (entity === null){
        req.user = user;
    } else {
        req.entity = entity;
        next();
        req.user = undefined;
    }
    next(); 
}).catch(function(e){
    console.log(e);
    res.status(401).send();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-14
    • 2020-01-29
    • 2010-12-08
    • 2012-05-08
    • 1970-01-01
    • 2011-11-19
    • 2013-04-07
    • 2018-05-30
    相关资源
    最近更新 更多