ForgeTotal.js 5
it

Total.js 5

Chiama servizi esterni con API() e i driver di NEWAPI()

Total.js 5 · total5@0.0.19 apiservicesintegrations Eseguita con Total.js 5

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 servizio name ('a,b' registra un driver per due nomi e NEWAPI(driver) registra quello default). NEWAPI('name', config, driver) conserva anche un oggetto config che ogni chiamata riceve come options.config.
  • Il driver è function(options, next). options.name è il servizio, options.schema l'operazione, options.data i dati e options.config la configurazione. Rispondi con next(error, response).
  • API('name', 'operation', data) restituisce un builder: concludilo con .callback($) (la risposta va all'azione $), .callback(function(err, response) {}) o await ....promise($). .configure({ key: value }) aggiunge a options.config per 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.
definitions/api.js
// 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);
});
controllers/weather.js
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 });
}