I'm fairly new to node.js and I'm trying to make a simple node.js REST client to act as an SDK between an API and a larger application.
This is the current code in the client SDK part corresponding to index.js
:
var unirest = require('unirest');
var config = require('config');
var host = config.get('api.host');
unirest.get(host + '/api/products?_format=json')
.headers({'Accept': 'application/json', 'Content-Type': 'application/json'})
.end(function (response) {
console.log(response.body);
module.exports.getProducts = function() {
return response.body;
}
});
If I execute in the terminal: node index.js
the console.log
command returns the expected result from the API call
However if I install the package in the main project (as a local dependency) it does not seem to work.
Here is the code from the index.js
in the main project:
var SDK = require('api-sdk-js');
var result = SDK.getProducts;
console.log(result);
In this case when I execute node index.js
the console.log
command returns undefined
for the result
variable, I suspect this is due to the GET
call in the SDK being asynchronous so it returns the value before there is a response.
I'm not sure how to fix this, any suggestions?
Alternatively it would also work for me a good example of a REST API client in node.js as an SDK (i.e., as a package able to be installed from another project).