Chiama servizi esterni con API() e i driver di NEWAPI()
API(name, schema, data, [$]) chiama un'operazione di un servizio esterno e NEWAPI() registra il driver che esegue la chiamata, così il codice delle tue azioni non dipende da come si raggiunge il servizio (HTTP, una libreria, una coda...).
NEWAPI('name', driver)registra il driver del servizioname('a,b'registra un driver per due nomi eNEWAPI(driver)registra quellodefault).NEWAPI('name', config, driver)conserva anche un oggettoconfigche ogni chiamata riceve comeoptions.config.- Il driver è
function(options, next).options.nameè il servizio,options.schemal'operazione,options.datai dati eoptions.configla configurazione. Rispondi connext(error, response). API('name', 'operation', data)restituisce un builder: concludilo con.callback($)(la risposta va all'azione$),.callback(function(err, response) {})oawait ....promise($)..configure({ key: value })aggiunge aoptions.configper quella chiamata e.error('text')fa fallire una risposta vuota con quel messaggio.- Se per il nome non è registrato alcun driver, la chiamata fallisce con
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 });
}