Reputation: 637
I'm trying to code an RESTfull API in nodejs which is basically around a controller/modele schema and I meet some problems about the async nature of nodejs:
Station.js: (controller)
'use strict';
var url = require('url');
var Stations = require('./StationsService');
module.exports.stationsGet = function stationsGet(req, res, next){
var result = Stations.stationsGet(req.swagger.params['arg']);
if(typeof result !== 'undefined') {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(result || {}, null, 2));
}
else
res.end();
};
StationService.js: (modele)
'use strict';
exports.stationsGet = function(param){
var data_output = {};
var sql = 'SELECT * FROM foo WHERE args = ${foo}';
db.execute(sql, {foo: param}, db.queryResult.any, function(result){
// 'result' containing the query data
});
// Ideally: data_output = result;
return data_output;
}
The problem is if I use callback on my db.execute to continue, I have to give all the controller context (res, ...) to reply back to the client, and it break the modele/controller schema since my modele does the remaining controller work.
Is there a (easy?) way to get the result of the query in stationsGet() and then returning it? Is it really against the nodejs nature and if so how to adopt the correct behavior in that case?
PS: I'm using swagger which has generated the files and base structure for nodejs.
Upvotes: 0
Views: 283
Reputation: 2476
You should use a callback in this case (take a look at promises as well)
your controller will look like this:
'use strict';
var url = require('url');
var Stations = require('./StationsService');
module.exports.stationsGet = function stationsGet(req, res, next){
Stations.stationsGet(req.swagger.params['arg'], function(err, result) {
if(typeof result !== 'undefined') {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(result || {}, null, 2));
}
else
res.end();
});
};
And the model you made must accept a callback as a last parameter, and you return err
and the result
like follows:
'use strict';
exports.stationsGet = function(param, cb){
var data_output = {};
var sql = 'SELECT * FROM foo WHERE args = ${foo}';
db.execute(sql, {foo: param}, db.queryResult.any, function(result){
cb(null, result); // first parameter is the error and the second is the result, this is pretty standard in node
});
}
I hope this helps you
Upvotes: 1