Call external services with API() and NEWAPI() drivers
API(name, schema, data, [$]) calls an operation of an external service and NEWAPI() registers the driver that makes the call, so the code of your actions does not depend on how the service is reached (HTTP, a library, a queue...).
NEWAPI('name', driver)registers the driver of the servicename('a,b'registers one driver for two names, andNEWAPI(driver)registers thedefaultone).NEWAPI('name', config, driver)also stores aconfigobject that every call receives asoptions.config.- The driver is
function(options, next).options.nameis the service,options.schemathe operation,options.datathe data andoptions.configthe configuration. Answer withnext(error, response). API('name', 'operation', data)returns a builder: finish it with.callback($)(the response goes to the action$),.callback(function(err, response) {})orawait ....promise($)..configure({ key: value })adds tooptions.configfor that call, and.error('text')makes an empty answer fail with that message.- If no driver is registered for the name the call fails with
API is not initialized.
// The driver of a fake weather service: in a real one this would be an HTTP request
NEWAPI('weather', { unit: 'C' }, function(options, next) {
if (options.schema === 'forecast')
next(null, { city: options.data.city, temperature: 21, unit: options.config.unit, service: options.name });
else
next('Unknown operation ' + options.schema);
});exports.install = function() {
ROUTE('GET /forecast/', forecast);
ROUTE('GET /forecast-fahrenheit/', fahrenheit);
ROUTE('GET /unknown/', unknown);
ROUTE('GET /missing/', missing);
ROUTE('GET /promise/', promise);
};
function forecast($) {
API('weather', 'forecast', { city: $.query.city }).callback($);
}
function fahrenheit($) {
API('weather', 'forecast', { city: $.query.city }).configure({ unit: 'F' }).callback($);
}
function unknown($) {
API('weather', 'rain', {}).callback($);
}
function missing($) {
API('nobody', 'forecast', {}).callback($);
}
async function promise($) {
const data = await API('weather', 'forecast', { city: 'Oslo' }).promise($);
$.json({ city: data.city, same: true });
}