ForgeTotal.js 5
pt

Total.js 5

Chame serviços externos com API() e os drivers de NEWAPI()

Total.js 5 · total5@0.0.19 apiservicesintegrations Executada com o Total.js 5

API(name, schema, data, [$]) chama uma operação de um serviço externo e NEWAPI() regista o driver que faz a chamada, de modo que o código das suas ações não depende de como se chega ao serviço (HTTP, uma biblioteca, uma fila...).

  • NEWAPI('name', driver) regista o driver do serviço name ('a,b' regista um driver para dois nomes e NEWAPI(driver) regista o default). NEWAPI('name', config, driver) guarda também um objeto config que cada chamada recebe como options.config.
  • O driver é function(options, next). options.name é o serviço, options.schema a operação, options.data os dados e options.config a configuração. Responda com next(error, response).
  • API('name', 'operation', data) devolve um builder: termine-o com .callback($) (a resposta vai para a ação $), .callback(function(err, response) {}) ou await ....promise($). .configure({ key: value }) acrescenta a options.config para essa chamada e .error('text') faz com que uma resposta vazia falhe com essa mensagem.
  • Se não houver nenhum driver registado para o nome, a chamada falha com 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 });
}