Volajte externé služby cez API() a drivery NEWAPI()
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žbyname('a,b'zaregistruje jeden driver pre dva názvy aNEWAPI(driver)zaregistrujedefault).NEWAPI('name', config, driver)uloží aj objektconfig, ktorý každé volanie dostane akooptions.config.- Driver je
function(options, next).options.nameje služba,options.schemaoperácia,options.datadáta aoptions.configkonfigurácia. Odpovedzte ceznext(error, response). API('name', 'operation', data)vráti builder: ukončite ho cez.callback($)(odpoveď ide do akcie$),.callback(function(err, response) {})aleboawait ....promise($)..configure({ key: value })pridá dooptions.configpre 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.
// 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);
});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 });
}