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:
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