ForgeTotal.js 5
es

Total.js 5

Llama a servicios externos con API() y los drivers de NEWAPI()

Total.js 5 · total5@0.0.19 apiservicesintegrations Ejecutada con Total.js 5

API(name, schema, data, [$]) llama a una operación de un servicio externo y NEWAPI() registra el driver que hace la llamada, de modo que el código de tus acciones no depende de cómo se llega al servicio (HTTP, una librería, una cola...).

  • NEWAPI('name', driver) registra el driver del servicio name ('a,b' registra un driver para dos nombres y NEWAPI(driver) registra el default). NEWAPI('name', config, driver) guarda además un objeto config que cada llamada recibe como options.config.
  • El driver es function(options, next). options.name es el servicio, options.schema la operación, options.data los datos y options.config la configuración. Responde con next(error, response).
  • API('name', 'operation', data) devuelve un builder: termínalo con .callback($) (la respuesta va a la acción $), .callback(function(err, response) {}) o await ....promise($). .configure({ key: value }) añade a options.config para esa llamada y .error('text') hace que una respuesta vacía falle con ese mensaje.
  • Si no hay ningún driver registrado para el nombre, la llamada falla con 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 });
}