Reputation: 5513
I am trying to organise my code in 3 files
so that for a GET
request, I can respond with the resulting rows. I am simply unable to wrap my head around the callback functions. How can I return the resulting rows to the client ?
File: db_queries.js
function getUserData (userId, fn){
client.query("select * from participationTable where ? in (userId1, userId2)", userId, function(err,rows){
if (err) {
return fn(new Error('(customError) unable to find ongoing games'));
} else {
return fn(null, rows);
}
});
}
module.exports.getUserData = getUserData;
File: general_functions.js
var db = require('./db_queries');
function getUserParticipationDeatils(req, function(err, rows){
db.getUserData(req.user.userId, function(err, rows){
if (err){ return done(err); }
// 'rows' is accessible here
// but how can I send it ?
});
});
module.exports.getUserParticipationDeatils = getUserParticipationDeatils;
File: basic_routes.js
var general_functions = require('./general_functions');
app.get('/getUserParticipation', function (req, res) {
general_functions.getUserParticipationDeatils(req, function(err, rows){
if (err){ return done(err); }
return res.send(JSON.stringify(rows));
});
});
Please help me structure the functions in the file general_functions.js
Upvotes: 0
Views: 300
Reputation: 2418
Change your getUserParticipationDeatils to accept a callback fn just like your getUserData function.
Something like this:
var db = require('./db_queries');
function getUserParticipationDeatils(req, fn){
db.getUserData(req.user.userId, function(err, rows){
if (err){ return fn(err); }
fn(null, rows);
});
});
module.exports.getUserParticipationDeatils = getUserParticipationDeatils;
Upvotes: 1