# Chame serviços externos com API() e os drivers de NEWAPI()

> Registe um driver para um serviço com NEWAPI() e chame-o a partir das ações com API(name, schema, data), com o mesmo estilo de callback, erro e promessa do query builder.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: pt
Content-SHA256: c76f6bedda5479f469628bc78ceb671a87ac257af5daaef83dbeb0603711c18a
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

`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ço `name` (`'a,b'` regista um driver para dois nomes e `NEWAPI(driver)` regista o `default`). `NEWAPI('name', config, driver)` guarda também um objeto `config` que cada chamada recebe como `options.config`.
- O driver é `function(options, next)`. `options.name` é o serviço, `options.schema` a operação, `options.data` os dados e `options.config` a configuração. Responda com `next(error, response)`.
- `API('name', 'operation', data)` devolve um builder: termine-o com `.callback($)` (a resposta vai para a ação `$`), `.callback(function(err, response) {})` ou `await ....promise($)`. `.configure({ key: value })` acrescenta a `options.config` para 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`.

```js 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);
});
```

```js 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 });
}

```
