ForgeTotal.js 5
en

Total.js 5

Call external services with API() and NEWAPI() drivers

Total.js 5 · total5@0.0.19 apiservicesintegrations Executed against Total.js 5

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 service name ('a,b' registers one driver for two names, and NEWAPI(driver) registers the default one). NEWAPI('name', config, driver) also stores a config object that every call receives as options.config.
  • The driver is function(options, next). options.name is the service, options.schema the operation, options.data the data and options.config the configuration. Answer with next(error, response).
  • API('name', 'operation', data) returns a builder: finish it with .callback($) (the response goes to the action $), .callback(function(err, response) {}) or await ....promise($). .configure({ key: value }) adds to options.config for 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.
definitions/api.js
// 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);
});
controllers/weather.js
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 });
}