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).
Your unirest call should really be inside your module.exports.getProducts
method.
Due to the call being asynchronous, you can't just return
from it. You need some sort of callback.
module.exports.getProducts = function(callback) {
unirest.get(host + '/api/products?_format=json')
.headers({'Accept': 'application/json', 'Content-Type': 'application/json'})
.end(function (response) {
callback(response.body);
});
};
You'd then use it like so:
var SDK = require('./api-sdk-js');
SDK.getProducts(function(products) {
console.log(products); // Should contain data from the callback
});
Read How do I return the response from an asynchronous call? for other alternatives to asynchronous JavaScript.