Skip to content Skip to sidebar Skip to footer

Express Node.js - Receiving Redis Callback, Executing Promises

I have a Node/Express routing function which executes a Redis call in another module. I want to perform a complex Redis function in one node module and send a simple callback sayin

Solution 1:

I figured this out. I used the Q library to perform all the functions instead of client.multi().exec(). This allowed a clean execution of all the redis post commands and then allowed for me to retrieve the information.

In the routes.js file, I only had a brief bit of code. Everything is executed in the doctorDB.js file.

routes.js

app.post('/addDoctorInfo', ensureLoggedIn('/login'), function(req, res, next){
        return doctorDB.addDoctor(req.body.id, req.body.doc, req, res, next);
});

doctorDB.js

var addDoctor = function addDoctor(id, doc, req, res, next){
    var fields = Object.keys(doc.fields);

    function middleName(id, doc){
        if (doc.middleName){ return client.hset(id, "middleName", doc.middleName); }
        else { return; }
    }

    return Q.all([Q.ninvoke(client, 'sadd', 'Doctors', id),
                    Q.ninvoke(client, 'hmset', id, "lastName", doc.lastName, "firstName", doc.firstName, "email", doc.email, "university", doc.university, "work", doc.work),
                    Q.ninvoke(client, 'sadd', id + ':fields', fields),
                    middleName(id, doc)]).then(function(x){
                        return getInfo(id, req, res, next);;
                    }, function (err) { res.status(404); });
};

This gets passed on to the function getInfo() which sends a response to the client side:

var redisHGetAll = Q.nbind(client.hgetall, client);

var getInfo = functiongetInfo(id, req, res, next){
    returnredisHGetAll(id).then(function(x){
        returnfindByMatchingProperties(x);
    }, function (err) { res.status(404); }).then(function(){
        return client.smembers(id + ':fields', function(err, reply){
            data['fields'] = reply;
            res.setHeader('Content-Type', 'application/json');
            res.end(JSON.stringify(data));
        });
    }, function (err) { res.status(404); })
};

functionfindByMatchingProperties(x) {
    for (var y in x){
        checkData(y, x[y]);
    }       

    functioncheckData(y, z){
        for (var d in data){
            if (d === y){
                data[d] = z;
            }
        }
    }
}

var data = {
    lastName: null,
    firstName: null,
    middleName: null,
    email: null,
    university: null,
    work: null,
    fields: null
};

Post a Comment for "Express Node.js - Receiving Redis Callback, Executing Promises"