Roep externe diensten aan met API() en de drivers van NEWAPI()
API(name, schema, data, [$]) roept een bewerking van een externe dienst aan en NEWAPI() registreert de driver die de aanroep uitvoert, zodat de code van je acties niet afhangt van hoe de dienst wordt bereikt (HTTP, een bibliotheek, een wachtrij...).
NEWAPI('name', driver)registreert de driver van de dienstname('a,b'registreert één driver voor twee namen enNEWAPI(driver)registreert dedefault).NEWAPI('name', config, driver)bewaart ook eenconfig-object dat elke aanroep ontvangt alsoptions.config.- De driver is
function(options, next).options.nameis de dienst,options.schemade bewerking,options.datade gegevens enoptions.configde configuratie. Antwoord metnext(error, response). API('name', 'operation', data)geeft een builder terug: sluit hem af met.callback($)(het antwoord gaat naar de actie$),.callback(function(err, response) {})ofawait ....promise($)..configure({ key: value })voegt toe aanoptions.configvoor die aanroep en.error('text')laat een leeg antwoord mislukken met die melding.- Als er voor de naam geen driver is geregistreerd, mislukt de aanroep met
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 });
}