ForgeTotal.js 5
sk

Total.js 5

Volajte externé služby cez API() a drivery NEWAPI()

Total.js 5 · total5@0.0.19 apiservicesintegrations Spustené s Total.js 5

API(name, schema, data, [$]) volá operáciu externej služby a NEWAPI() registruje driver, ktorý volanie vykoná, takže kód vašich akcií nezávisí od toho, ako sa k službe dostanete (HTTP, knižnica, fronta...).

  • NEWAPI('name', driver) zaregistruje driver služby name ('a,b' zaregistruje jeden driver pre dva názvy a NEWAPI(driver) zaregistruje default). NEWAPI('name', config, driver) uloží aj objekt config, ktorý každé volanie dostane ako options.config.
  • Driver je function(options, next). options.name je služba, options.schema operácia, options.data dáta a options.config konfigurácia. Odpovedzte cez next(error, response).
  • API('name', 'operation', data) vráti builder: ukončite ho cez .callback($) (odpoveď ide do akcie $), .callback(function(err, response) {}) alebo await ....promise($). .configure({ key: value }) pridá do options.config pre dané volanie a .error('text') spôsobí, že prázdna odpoveď zlyhá s touto správou.
  • Ak pre názov nie je zaregistrovaný žiadny driver, volanie zlyhá s 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 });
}