How to make synchronous queries with Sequelize in Node.js

2

I started porting Node.js recently and I'm using the division of logic into modules. I have UserSessionController that validates if 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 making the call the code follows without receiving the 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();
}

As this call is executed in 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 Javascript call run in a synchronous way ?

    
asked by anonymous 29.05.2014 / 15:57

1 answer

4

The "beauty" of the Node lies in its asynchronicity. Pass two callback functions to getUserSession , like this:

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);
                   };
               });
}    

As I can not test, check if return is really needed before the callbacks call.
You may also want to return the 403 - Forbidden code if the user is not authenticated.

    
30.05.2014 / 14:40