Sudhir Jena Sudhir Jena - 4 months ago 25
Node.js Question

Consolidate multiple callbacks in node.js module exports

I have a sails.js service which uses restler (rest-client) to make api calls to external apis and fetch data.

The module looks like this:

var rest = require('restler');

module.exports = {
config: {
url: sails.config.remote_api.base_url.concat('/countries'),
rejectUnauthorized: sails.config.remote_api.validateSsl,
options: { 'Content-Type': 'application/json' }
},
find: function(headers, payload, callback) {
var request = rest.get(this.config.url, this.config.options);
sails.log.info('Outgoing Request', { log_id: headers[x - request - id], method: request.method, host: request.host, url: request.url });

request.on('2XX', function(data, response) {
callback(data, response);
});
}
}


In the above code request.on('2XX',...) handles the event emitted when response code is in the 200 series.

When we add other handlers for events emitted when response code is in 300, 400, 500 series...this creates a duplication of same callback function for each of the blocks. For e.g.

var rest = require('restler');
module.exports = {
config: {
url: sails.config.remote_api.base_url.concat('/countries'),
rejectUnauthorized: sails.config.remote_api.validateSsl,
options: { 'Content-Type': 'application/json' }
},
find: function(headers, payload, callback) {
var request = rest.get(this.config.url, this.config.options);
sails.log.info('Outgoing Request', { log_id: headers[x - request - id], method: request.method, host: request.host, url: request.url });

request.on('2XX', function(data, response) {
callback(data, response);
});

request.on('3XX', function(data, response) {
callback(data, response);
});

request.on('4XX', function(data, response) {
callback(data, response);
});

request.on('5XX', function(data, response) {
data = {};
data.succeeded = false;
data.failureCode = 'SYSTEM ERROR';
data.failureReason = 'A system error has occurred. Please try again. If the problem persists contact support';
callback(data, response);
});

request.on('error', function(data, response) {
data.succeeded = false;
data.failureCode = 'SERVICE UNAVAILABLE';
data.failureReason = 'The service is temporarily unavailable. Please try again later.';
callback(data, response);
});
}
}


How do we avoid the duplication of the following lines?

function(data, response) {
callback(data, response);
}

Answer

No you really shouldn't. You have been basically handling different event like 2XX, 3XX etc. Each event is handled separately and that is a good practice. Anymore simplification could damage the neat design.

Though you can directly use callback instead of

function(data, response) {
    callback(data, response);
}

like this

request.on('2XX', callback);
Comments