How to make synchronous queries with Sequelize on Node.js

Asked

Viewed 866 times

2

I started to stew Node.js not long ago and I am using the division of logic into modules. I have a UserSessionController validates whether the user session is still valid:

module.exports.getUserSession = function ( userToken ) {
    models.UserSession.find( {where : Sequelize.and(
        { token: userToken }, { dataExpira { lte: Date() } }) } ).complete ( function (err, user) {
            if (!!err) {
                console.log('Ocorreu um erro ao buscar a sessão do usuário:', err);
                return null;
            } else {
                return user;
            };
    })
}

but when I try to execute this call from another module, when calling the code goes without receiving Return, because it will only be processed when the query is completed.

usuarioLogado = userSession.getUserSession(token)
if (!!usuarioLogado) { //aqui usuarioLogado está undefined
  //faz a ação
} else {
  res.send(401, "Você deve estar logado para realizar alterações.");
  next();
}

how this call is executed on a webservice REST the response to the WS client occurs before the query is executed in the database.

Is there a way to make a call Javascript is executed in a manner synchronous?

1 answer

6


The "beauty" of the Node is in its asynchronicity. Pass two callback functions to getUserSession, thus:

userSession.getUserSession(token, 
    function(err){
        res.send(401, "Você deve estar logado para realizar alterações.");
        next();
    }, 
    function(user){
        // faz alguma coisa com o usuario retornado
    });

And in function:

module.exports.getUserSession = function (userToken, failure, success) {
    models.UserSession
               .find({where : Sequelize.and({token: userToken}, 
                                            {dataExpira : {lte: Date()}})
                      })
               .complete(function (err, user) {
                   if (!!err) {
                      return failure(err);
                   } else {
                      return success(user);
                   };
               });
}    

Since I can’t test, make sure you really need the return before the callbacks call.
Maybe you also want to return the code 403 - Forbidden if the user is not authenticated.

  • It worked perfectly. I’m trying to learn this asymchronism paradigm, because I’ve always worked with imperative liguagens. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.