node.js - Setting a function callback fram an async request -
good morning all,
i have been looking answer on boards, noob brain can't make sense of it.
i have function in models/user.js
module.exports.getuserbyusername = function(username, callback){ var retuser = new user; sql.connect(dbconfig, function(err) { if (err) { console.log(err); callback(); } // create request object var request = new sql.request(); request.input('ip_username', sql.nvarchar, username) // query database , records request.query('select * [portal_users] username = @ip_username', function(err, recordset) { if (err) { console.log(err); return; } else { var user = new user(recordset.recordset[0].username,recordset.recordset[0].password,recordset.recordset[0].email,recordset.recordset[0].name); user.addid(recordset.recordset[0].id); retuser = user; } callback(); // send records response //res.send(recordset); }); }); function callback() { sql.close(); return retuser; }; }
and code in routes/user.js
passport.use(new localstrategy( function(username, password, done) { user.getuserbyusername(username, function(err, user){ if(err) throw err; if(!user){ return done(null, false, {message: 'unknown user'}); } user.comparepassword(password, user.password, function(err, ismatch){ if(err) throw err; if(ismatch){ return done(null, user); } else { return done(null, false, {message: 'invalid password'}); } }); }); }));
i have been modifying example github uses mongodb db connection, use ms sql. function calling database , returning correct values. don't know how initiate callback can pass retuser object original function processing , logging in.
i did moment try not using callback , using standard return type of function, realised given async nature wouldn't work.
any here appreciated.
thanks
ok managed figure out using post: node.js npm mssql function returning undefined
my new code is:
module.exports.getuserbyusername = function(username, callback){ var connection = new sql.connectionpool(dbconfig, function(err) { if (err) { console.log(err); callback(err); return } // create request object var request = new sql.request(connection); request.input('ip_username', sql.nvarchar, username) // query database , records request.query('select * [portal_users] username = @ip_username', function(err, recordset) { if (err) { console.log(err); callback(err,recordset); return; } else { var user = new user(recordset.recordset[0].username,recordset.recordset[0].password.replace(/ /g,''),recordset.recordset[0].email,recordset.recordset[0].name); user.addid(recordset.recordset[0].id); callback(err,user); } sql.close(); // send records response //res.send(recordset); }); }); }
Comments
Post a Comment