Appeler des services externes avec API() et les pilotes de NEWAPI()
API(name, schema, data, [$]) appelle une opération d'un service externe et NEWAPI() enregistre le pilote qui fait l'appel, de sorte que le code de vos actions ne dépend pas de la façon dont on atteint le service (HTTP, une bibliothèque, une file...).
NEWAPI('name', driver)enregistre le pilote du servicename('a,b'enregistre un pilote pour deux noms etNEWAPI(driver)enregistre celui par défaut,default).NEWAPI('name', config, driver)conserve aussi un objetconfigque chaque appel reçoit en tant queoptions.config.- Le pilote est
function(options, next).options.nameest le service,options.schemal'opération,options.datales données etoptions.configla configuration. Répondez avecnext(error, response). API('name', 'operation', data)renvoie un builder : terminez-le avec.callback($)(la réponse va à l'action$),.callback(function(err, response) {})ouawait ....promise($)..configure({ key: value })ajoute àoptions.configpour cet appel et.error('text')fait échouer une réponse vide avec ce message.- Si aucun pilote n'est enregistré pour le nom, l'appel échoue avec
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 });
}