Chame serviços externos com API() e os drivers de NEWAPI()
API(name, schema, data, [$]) chama uma operação de um serviço externo e NEWAPI() regista o driver que faz a chamada, de modo que o código das suas ações não depende de como se chega ao serviço (HTTP, uma biblioteca, uma fila...).
NEWAPI('name', driver)regista o driver do serviçoname('a,b'regista um driver para dois nomes eNEWAPI(driver)regista odefault).NEWAPI('name', config, driver)guarda também um objetoconfigque cada chamada recebe comooptions.config.- O driver é
function(options, next).options.nameé o serviço,options.schemaa operação,options.dataos dados eoptions.configa configuração. Responda comnext(error, response). API('name', 'operation', data)devolve um builder: termine-o com.callback($)(a resposta vai para a ação$),.callback(function(err, response) {})ouawait ....promise($)..configure({ key: value })acrescenta aoptions.configpara essa chamada e.error('text')faz com que uma resposta vazia falhe com essa mensagem.- Se não houver nenhum driver registado para o nome, a chamada falha com
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 });
}