Rahul Arora
Rahul Arora

Reputation: 4533

Sequelize better way of writing this code

I am using NodeJS and sequelize. I have two types of login in my application. One is normal user login and one is company login.

The code below looks for the token in the company table first, if it does not exist it moves to the user table to find it.

This way I know who has logged in to the system.

Is there a better way to do it?

OR

Is there a way where I can simultaneously search in two tables rather than waiting for sequelize to search in one table and then do the other?

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!

Upvotes: 0

Views: 116

Answers (1)

Bergi
Bergi

Reputation: 664579

Yes, you can easily search in both tables at once and wait for both results using 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();
});

Upvotes: 2

Related Questions