# Volajte externé služby cez API() a drivery NEWAPI()

> Zaregistrujte driver pre službu pomocou NEWAPI() a volajte ho z akcií pomocou API(name, schema, data) s rovnakým štýlom callbacku, chyby a promise ako query builder.

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

`API(name, schema, data, [$])` volá operáciu externej služby a `NEWAPI()` registruje **driver**, ktorý volanie vykoná, takže kód vašich akcií nezávisí od toho, ako sa k službe dostanete (HTTP, knižnica, fronta...).

- `NEWAPI('name', driver)` zaregistruje driver služby `name` (`'a,b'` zaregistruje jeden driver pre dva názvy a `NEWAPI(driver)` zaregistruje `default`). `NEWAPI('name', config, driver)` uloží aj objekt `config`, ktorý každé volanie dostane ako `options.config`.
- Driver je `function(options, next)`. `options.name` je služba, `options.schema` operácia, `options.data` dáta a `options.config` konfigurácia. Odpovedzte cez `next(error, response)`.
- `API('name', 'operation', data)` vráti builder: ukončite ho cez `.callback($)` (odpoveď ide do akcie `$`), `.callback(function(err, response) {})` alebo `await ....promise($)`. `.configure({ key: value })` pridá do `options.config` pre dané volanie a `.error('text')` spôsobí, že prázdna odpoveď zlyhá s touto správou.
- Ak pre názov nie je zaregistrovaný žiadny driver, volanie zlyhá s `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 });
}

```
