Volejte externí služby přes API() a ovladače NEWAPI()
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žbyname('a,b'zaregistruje jeden ovladač pro dva názvy aNEWAPI(driver)zaregistruje výchozí,default).NEWAPI('name', config, driver)uloží také objektconfig, který každé volání dostane jakooptions.config.- Ovladač je
function(options, next).options.nameje služba,options.schemaoperace,options.datadata aoptions.configkonfigurace. Odpovězte přesnext(error, response). API('name', 'operation', data)vrátí builder: ukončete jej přes.callback($)(odpověď jde do akce$),.callback(function(err, response) {})neboawait ....promise($)..configure({ key: value })přidá dooptions.configpro 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.
// 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 });
}