Wednesday, 10 May 2017

Node.js socket.io return function value

I just started working on node.js and socket.io, I am having a little trouble understanding callbacks,what I am trying to do is call a function from get_profile in socket.io verifyToken(token). Verify token is not return json response.

I read that because of node.js async nature its better to use a callback function to get the desired data once the complete execution is done.

Now I am having trouble retrieving the value that verifyToken() is returning,I have no proper idea how to do it, well the callback function has the value but how do I get the value from there?

    io.on('connection', function (socket) {

    console.log(socket['id'] + ' has connected!');s

    socket.on('get_profile', function (data, token) {

    rslt = verifyToken(token);
    console.log(rslt);

    return false;
    var msg = []

    if (validation.isEmpty(data)) {
        msg.push({'field': 'user_id', 'msg': 'User id is not empty.'});
    }

    if (msg.length == 0) {
        dbMongo.profileDetail(data, function (res) {
            socket.emit('set_profile', res);
        });
    } else {
        socket.emit('set_profile', {'error': 1, 'message': msg, 'data': null, 'status': 406});
    }
});
var verifyToken = function verifyToken(token, callback) {

    jwt.verify(token, config.appSecret, function (err, decoded) {
        if (err) {

        } else {
            dbMongo.userAuthenticate(decoded, function (res) {
                callback(res);
            });
        }
    });
}

function getAuthenticate(res) {
    res['token'] = jwt.sign({'email': res.data.email, 'userId':res.data.user_id},   config.appSecret);
    return res;
}

});

http.listen(config.server.port, function () {
    console.log('listening on *:' + config.server.port);
});

Other file have a function :

exports.userAuthenticate = function userAuthenticate(data, callback) {

MongoClient.connect(Mongo_url, function (err, db) {
    assert.equal(null, err); 
    db.collection('users').findOne({email: data.email, user_id: parseInt(data.userId)}, function (err, res) { 
        if (err) {
            callback({'error': 1, 'message': 'Internal server error! ' + err, 'data': null, 'status': 500});
        } else if (res == null) {
            callback({'error': 1, 'message': 'Unauthorised User', 'data': null, 'status': 401});
        } else {
            callback({'error': 0, 'message': 'Successfull authenticate', 'data': null, 'status': 200});
        }
    });
});

}



via yogesh kumar

No comments:

Post a Comment