ForgeTotal.js 5
cs

Total.js 5

Volejte externí služby přes API() a ovladače NEWAPI()

Total.js 5 · total5@0.0.19 apiservicesintegrations Spuštěno s Total.js 5

API(name, schema, data, [$]) volá operaci externí služby a NEWAPI() registruje ovladač, který volání provede, takže kód vašich akcí nezávisí na tom, jak se ke službě dostanete (HTTP, knihovna, fronta...).

  • NEWAPI('name', driver) zaregistruje ovladač služby name ('a,b' zaregistruje jeden ovladač pro dva názvy a NEWAPI(driver) zaregistruje výchozí, default). NEWAPI('name', config, driver) uloží také objekt config, který každé volání dostane jako options.config.
  • Ovladač je function(options, next). options.name je služba, options.schema operace, options.data data a options.config konfigurace. Odpovězte přes next(error, response).
  • API('name', 'operation', data) vrátí builder: ukončete jej přes .callback($) (odpověď jde do akce $), .callback(function(err, response) {}) nebo await ....promise($). .configure({ key: value }) přidá do options.config pro dané volání a .error('text') způsobí, že prázdná odpověď selže s touto zprávou.
  • Pokud pro název není zaregistrován žádný ovladač, volání selže 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 });
}