I'm building an MVC application in Node, Express, Request...etc with a controller to repository stack. In the repo, I'm connecting with request (Simplified HTTP request client) to an external API that returns JSON.
I have the following code:
// The repository
var request = require('request');
module.exports.getById= function (id) {
var options = {
url: 'http://myurl...' + id,
headers: {
'Accept': 'application/json',
'Accept-Language': 'en-US',
}
};
request(options, callback);
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var data = JSON.parse(body);
return data;
} else {
res.send(404); // HTTP STATUS
console.log("ERROR: " + error);
}
}
};
// The Service
var myRepository = require('../repositories/myRepository');
module.exports.getById = function (id) {
return myRepository.getById(id);
};
How do I return data to the service, that returns it to the controller that renders it in the view? Return data from within the callback doesn't work. It also seems that I can't pass an additional callback method to the request callback in order to return it.