Spanish Total.js
Italiano
Documentazione Per agenti IA
Indice

Richieste HTTP

RESTBuilder, REQUEST(), AJAX(), DOWNLOAD() e Total.download().

.md GitHub
In questa pagina

Le funzioni globali e la classe RESTBuilder per le richieste HTTP verso altri servizi. Per un'introduzione con esempi leggi la guida Richieste HTTP. Il client WebSocket OPENCLIENT() ha una pagina propria: OpenClient.

API

method

REQUEST(options, [callback])

Invia una richiesta HTTP con il pieno controllo delle opzioni.
ParametroTipoDescrizione
options.url String L'URL della richiesta. Le credenziali nell'URL (https://user:password@host/) vengono inviate come Authorization: Basic; i caratteri codificati con percentuale al loro interno vengono prima decodificati.
options.method? String Il metodo HTTP in maiuscolo. Predefinito: 'GET'
options.headers? Object Header della richiesta. L'oggetto viene copiato, quindi il tuo oggetto non viene modificato.
options.type? String Imposta Content-Type: 'json', 'urlencoded', 'xml', 'html', 'plain' o 'text', 'raw' (application/octet-stream).
options.body? String|Buffer Il body della richiesta. Una stringa viene inviata come UTF-8; Content-Length viene impostato per te.
options.query? Object|String Aggiunto all'URL come query string.
options.cookies? Object Cookie da inviare, come { name: value }.
options.cook? Boolean Salva i cookie della response in options.cookies, così lo stesso oggetto options li invia con la richiesta successiva.
options.timeout? Number Timeout in millisecondi; 0 lo disattiva. Predefinito: 8000
options.encoding? String Codifica di un body testuale. 'binary' restituisce un Buffer. Predefinito: 'utf8'
options.xhr? Boolean Aggiunge X-Requested-With: XMLHttpRequest.
options.files? Array File per una richiesta multipart/form-data: [{ name, filename, buffer | path | url }]. options.body è quindi un oggetto di campi aggiuntivi del form.
options.compress? String Comprime il body: 'gzip' o 'deflate', e imposta Content-Encoding.
options.encrypt? String Una chiave: il body viene cifrato con essa e la risposta testuale viene decifrata con essa.
options.writer? Function function(req) scrive il body da sé: riceve la richiesta di Node.js, scrive i dati e chiama req.end(). body e files non vengono quindi usati.
options.custom? Boolean Restituisce response.stream invece di leggere il body.
options.noredirect? Boolean Non segue i redirect; la callback riceve la risposta 301/302.
options.keepalive? Boolean Usa un agent keep-alive condiviso (uno per HTTP, uno per HTTPS).
options.resolve? Boolean Risolve l'hostname con una cache DNS. options.dnscache fa lo stesso. Viene saltato per localhost e gli indirizzi IP.
options.proxy? String Un proxy per questa richiesta, come 'host:port' o 'http://host:port'. Con http://user:password@host:port le credenziali vengono inviate come Proxy-Authorization: Basic.
options.insecure? Boolean Accetta certificati TLS non validi o autofirmati.
options.key? Buffer Chiave TLS del client.
options.cert? Buffer Certificato TLS del client.
options.dhparam? Buffer Parametri Diffie-Hellman TLS.
options.unixsocket? Object { socket, path } per inviare la richiesta attraverso un socket Unix invece di url.
options.ondata? Function function(chunk, percentage) per ogni chunk ricevuto.
options.onprogress? Function function(percentage); la percentuale è nota solo con Content-Length.
options.callback? Function function(err, response), al posto del secondo argomento.
callback? Function function(err, response).

Restituisce Promise Una promise quando non viene fornita alcuna callback; altrimenti nulla.

Invia una richiesta HTTP descritta da options. La callback riceve (err, response); senza callback (nell'argomento o in options.callback) restituisce una promise che si risolve con response.

L'oggetto response ha status, headers, body, host, origin (gli indirizzi IP risolti quando la cache DNS è attiva) e cookies (i cookie raccolti nei redirect). body è una stringa per i tipi text/* e application/* (decodificata con encoding) e un Buffer per gli altri tipi, oppure sempre un Buffer con encoding: 'binary'. Il body non viene interpretato: usa RESTBuilder o AJAX() per questo.

Con custom: true la callback viene eseguita appena arrivano gli header e la response ha stream (la response di Node.js) invece di body.

Errori: un errore di rete passa l'oggetto errore con response.status === 0; un timeout scaduto passa '408: Request Timeout' con response.status === 408; più di quattro redirect passano 'Too many redirects'; un URL senza hostname passa 'Invalid hostname', e una stringa che non è un URL lancia TypeError: Invalid URL. Un codice di stato 400 o superiore non è un errore: controlla response.status.

I redirect 301 e 302 vengono seguiti (i cookie del redirect vengono inviati alla posizione successiva). Le richieste usano il proxy della chiave di configurazione $proxyrequest quando è impostata, tranne che per localhost, 127.0.0.1 e 0.0.0.0.

POST JSON
REQUEST({
	url: 'https://api.example.com/orders/',
	method: 'POST',
	type: 'json',
	body: JSON.stringify({ id: 'p100', count: 2 })
}, function(err, response) {
	if (err || response.status !== 200)
		return;
	var order = response.body.parseJSON();
});
Con una promise
var response = await REQUEST({ url: 'https://example.com/robots.txt', timeout: 3000 });
console.log(response.status, response.body);
Caricare un file
REQUEST({
	url: 'https://files.example.com/upload/',
	method: 'POST',
	files: [{ name: 'file', filename: 'report.pdf', path: PATH.databases('report.pdf') }],
	body: { folder: 'reports' }
}, console.log);
Leggere uno stream
REQUEST({ url: 'https://cdn.example.com/video.mp4', custom: true }, function(err, response) {
	if (!err)
		response.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('video.mp4')));
});
Scrivere il body da te
REQUEST({
	url: 'https://api.example.com/import/',
	method: 'POST',
	type: 'plain',
	writer: function(req) {
		for (var line of lines)
			req.write(line + '\n');
		req.end();
	}
}, console.log);
method

AJAX('METHOD url', [data], [callback])

Invia una richiesta JSON e restituisce la risposta analizzata.
ParametroTipoDescrizione
url String 'METHOD url', per esempio 'POST [https://example.com/api/'](https://example.com/api/'`).
data? Object Dati inviati come JSON.
callback? Function function(err, response, meta).

Restituisce Promise Una promise quando non viene fornita alcuna callback.

Invia una richiesta e interpreta la risposta. Il primo argomento è il metodo e l'URL separati da uno spazio; senza metodo è GET. data viene inviato come body JSON. L'header X-Requested-With: XMLHttpRequest viene sempre aggiunto.

La risposta viene interpretata in base al suo Content-Type: JSON (application/json, text/json), dati URL-encoded e XML (application/xml, text/xml) diventano oggetti; gli altri tipi vengono restituiti come body grezzo. Un documento XML diventa un oggetto piatto: i nomi degli elementi annidati vengono uniti con _ (order_name), gli elementi ripetuti danno un array e gli attributi di un elemento sono in un oggetto sotto il suo nome con __ (order__). Un body XML vuoto dà {}. La callback riceve (err, response, meta), dove meta contiene status, headers e host.

Per uno stato 400 o superiore, err è il body interpretato (per un servizio Total.js l'array degli errori) e response è null. Senza callback la funzione restituisce una promise che si risolve con il body interpretato e viene rifiutata con err; un array di errori Total.js diventa un Error il cui messaggio contiene i messaggi di errore.

Callback
AJAX('POST https://api.example.com/login/', { email: 'peter@example.com' }, function(err, response, meta) {
	console.log(meta.status, response);
});
Promise
var products = await AJAX('GET https://api.example.com/products/?page=1');
Risposta XML
// the service answers <order id="100"><name>Book</name><items><item>A</item><item>B</item></items></order>
var order = await AJAX('GET https://api.example.com/orders/100/');
// { order__: { id: '100' }, order_name: 'Book', order_items_item: ['A', 'B'] }
method

DOWNLOAD(url, filename, [callback], [timeout])

Scarica un file remoto su disco.
ParametroTipoDescrizione
url String|Object L'URL, oppure { socket, path } per un socket Unix.
filename String Il percorso del file di destinazione.
callback? Function function(err, response).
timeout? Number Timeout in millisecondi. Predefinito: 8000

Restituisce Promise Una promise quando non viene fornita alcuna callback.

Scarica url e scrive il body in filename. La callback viene eseguita quando il file è scritto, con (err, response). response contiene status, headers, origin, filename e size (il numero di byte scritti). Il body viene salvato per ogni codice di stato, quindi controlla response.status.

url può essere anche un oggetto { socket, path } per un socket Unix. Le risoluzioni DNS vengono messe in cache. timeout è in millisecondi (8 secondi se non impostato). Senza callback la funzione restituisce una promise che si risolve con response.

Scaricare un'immagine
DOWNLOAD('https://cdn.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {
	if (!err && response.status === 200)
		console.log('Saved', response.filename);
});
Promise
var response = await DOWNLOAD('https://example.com/data.csv', PATH.tmp('data.csv'));
method

Total.download(url, filename, [callback], [timeout])

Il metodo del framework dietro DOWNLOAD().
ParametroTipoDescrizione
url String|Object L'URL, oppure { socket, path } per un socket Unix.
filename String Il percorso del file di destinazione.
callback? Function function(err, response).
timeout? Number Timeout in millisecondi. Predefinito: 8000

Restituisce Promise Una promise quando non viene fornita alcuna callback.

La stessa funzione di DOWNLOAD(). Scarica url e scrive il body in filename. La callback viene eseguita quando il file è scritto, con (err, response). response contiene status, headers, origin, filename e size (il numero di byte scritti). Il body viene salvato per ogni codice di stato, quindi controlla response.status.

url può essere anche un oggetto { socket, path } per un socket Unix. Le risoluzioni DNS vengono messe in cache. timeout è in millisecondi (8 secondi se non impostato). Senza callback la funzione restituisce una promise che si risolve con response.

Download
Total.download('https://example.com/export.json', PATH.tmp('export.json'), function(err, response) {
	console.log(err, response.status);
});
class

new RESTBuilder([url])

Un builder per le richieste verso servizi REST.
ParametroTipoDescrizione
url? String L'URL della richiesta.

Restituisce RESTBuilder Un nuovo builder.

Una classe globale. Un nuovo builder ha il metodo GET, un timeout di 10 secondi, la cache DNS attiva, l'header user-agent: Total.js/v... e accept: application/json, text/plain, text/plain, text/xml. Non viene inviato nulla finché non chiami callback(), promise(), stream() o exec().

Di solito inizi con un helper statico: RESTBuilder.GET(), POST(), PUT(), PATCH(), DELETE(), HEAD(), API(), url() o make(). RESTBuilder.url(url) equivale a new RESTBuilder(url).

Creare un builder
var builder = RESTBuilder.url('https://api.example.com/users/');
builder.header('X-Token', CONF.apitoken);
builder.callback(console.log);
method

RESTBuilder.make(fn)

Crea un builder e lo passa a una funzione.
ParametroTipoDescrizione
fn Function function(builder).

Restituisce RESTBuilder Il nuovo builder.

Crea un builder senza URL e chiama fn(builder). Imposta l'URL con builder.url(). Il metodo di istanza builder.make(fn) chiama fn con il builder come this e come argomento, per impostazioni riutilizzabili.

Costruire una richiesta
RESTBuilder.make(function(builder) {
	builder.url('https://api.example.com/users/');
	builder.post({ name: 'Peter' });
	builder.callback(console.log);
});
method

RESTBuilder.GET(url, [data])

Crea una richiesta GET.
ParametroTipoDescrizione
url String L'URL.
data? Object Inviato come query string.

Restituisce RESTBuilder Un nuovo builder.

Crea un builder con il metodo GET; data diventa la query string. Per una richiesta HEAD usa RESTBuilder.HEAD(url): non ha dati, il valore analizzato è un oggetto vuoto e leggi output.status e output.headers.

Query string
RESTBuilder.GET('https://api.example.com/products/', { page: 2, limit: 20 }).callback(function(err, response) {
	console.log(response);
});
HEAD
RESTBuilder.HEAD('https://example.com/').callback(function(err, response, output) {
	console.log(output.status, output.headers['last-modified']);
});
method

RESTBuilder.POST(url, [data])

Crea una richiesta POST.
ParametroTipoDescrizione
url String L'URL.
data? Object Inviato come body JSON.

Restituisce RESTBuilder Un nuovo builder.

Crea un builder con il metodo POST; data viene inviato come JSON. RESTBuilder.PUT(), RESTBuilder.PATCH() e RESTBuilder.DELETE() funzionano allo stesso modo con i rispettivi metodi.

POST JSON
RESTBuilder.POST('https://api.example.com/orders/', { productid: 'p100', count: 2 }).promise().then(function(order) {
	console.log(order.id);
});
method

RESTBuilder.PUT(url, [data])

Crea una richiesta PUT.
ParametroTipoDescrizione
url String L'URL.
data? Object Inviato come body JSON.

Restituisce RESTBuilder Un nuovo builder.

Crea un builder con il metodo PUT; data viene inviato come JSON.

PUT
RESTBuilder.PUT('https://api.example.com/products/p100/', { price: 99 }).callback(console.log);
method

RESTBuilder.PATCH(url, [data])

Crea una richiesta PATCH.
ParametroTipoDescrizione
url String L'URL.
data? Object Inviato come body JSON.

Restituisce RESTBuilder Un nuovo builder.

Crea un builder con il metodo PATCH; data viene inviato come JSON.

PATCH
RESTBuilder.PATCH('https://api.example.com/products/p100/', { price: 99 }).callback(console.log);
method

RESTBuilder.DELETE(url, [data])

Crea una richiesta DELETE.
ParametroTipoDescrizione
url String L'URL.
data? Object Inviato come body JSON.

Restituisce RESTBuilder Un nuovo builder.

Crea un builder con il metodo DELETE; data viene inviato come JSON.

DELETE
RESTBuilder.DELETE('https://api.example.com/products/p100/').callback(console.log);
method

RESTBuilder.API(url, name, [data])

Chiama un endpoint API di un'applicazione Total.js.
ParametroTipoDescrizione
url String L'URL dell'endpoint API.
name String Il nome dell'operazione API.
data? Object I dati dell'operazione.

Restituisce RESTBuilder Un nuovo builder.

Crea una richiesta POST per una route API di Total.js (ROUTE('API /api/ ...')). Il body è JSON: { schema: name, data: data }. name è il nome dell'API con parametri facoltativi, per esempio 'products_detail/p100'. builder.get(query) mantiene il POST e invia la query nel body come query, accanto a data. builder.compress() omette le chiavi del body il cui valore è null o undefined.

Chiamare un'API
RESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).callback(function(err, response) {
	console.log(err, response);
});
Con una query
RESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).get({ page: 2 }).callback(console.log);
// body: { data: { category: 'shoes' }, query: { page: 2 }, schema: 'products_list' }
method

builder.compress([value])

Omette i valori vuoti dal body di una richiesta RESTBuilder.API().
ParametroTipoDescrizione
value? Boolean false lo disattiva. Predefinito: true

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Senza argomento o con true, il body JSON di una richiesta RESTBuilder.API() viene scritto senza le chiavi il cui valore è null o undefined, così la richiesta è più piccola. compress(false) lo disattiva. Gli altri builder non sono interessati.

Body più piccolo
RESTBuilder.API(CONF.erpapi, 'orders_save', { id: 'A1', note: null, total: 120 }).compress().callback(console.log);
// data: { id: 'A1', total: 120 }
method

RESTBuilder.upgrade(fn)

Registra una funzione che modifica ogni builder prima che venga inviato.
ParametroTipoDescrizione
fn Function function(builder).

La funzione viene eseguita per ogni builder dell'applicazione subito prima che venga effettuata la richiesta, con il builder come argomento. Usala per header o token condivisi. Gli upgrade non possono essere rimossi.

Aggiungere un token a un servizio
RESTBuilder.upgrade(function(builder) {
	if (builder.url().startsWith(CONF.shopapi))
		builder.header('X-Token', CONF.shoptoken);
});
method

builder.url([url])

Imposta o legge l'URL.
ParametroTipoDescrizione
url? String Il nuovo URL.

Restituisce RESTBuilder|String Il builder, oppure l'URL quando viene chiamato senza argomento.

Con un argomento imposta l'URL e restituisce il builder; senza argomento restituisce l'URL corrente.

Leggere l'URL
var url = builder.url();
method

builder.method(method, [data])

Imposta il metodo HTTP.
ParametroTipoDescrizione
method String Il metodo HTTP.
data? Object Dati inviati come JSON.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Imposta il metodo (le minuscole vengono convertite in maiuscole). data viene inviato come JSON.

Scorciatoie: builder.get([query]) imposta GET e la query string; builder.post([data]), builder.put([data]), builder.patch([data]) e builder.delete([data]) impostano il metodo e il body (nel tipo impostato prima, JSON per impostazione predefinita); builder.head() imposta HEAD. I nomi in maiuscolo (builder.POST()) sono alias.

Scorciatoie
RESTBuilder.url('https://api.example.com/products/p100/').put({ price: 99 }).callback(console.log);
method

builder.json([data])

Invia i dati come JSON.
ParametroTipoDescrizione
data? Object I dati.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Imposta il tipo a JSON e il body a data (un oggetto viene serializzato quando la richiesta viene inviata). Una richiesta GET diventa POST.

Body JSON
RESTBuilder.url('https://api.example.com/users/').json({ name: 'Peter' }).callback(console.log);
method

builder.urlencoded([data])

Invia i dati come form URL-encoded.
ParametroTipoDescrizione
data? Object I campi del form.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Imposta Content-Type: application/x-www-form-urlencoded e il body; un oggetto viene codificato quando la richiesta viene inviata. Una richiesta GET diventa POST.

Form
RESTBuilder.url('https://example.com/login/').urlencoded({ name: 'peter', password: 'x' }).callback(console.log);
method

builder.xml([data])

Invia un body XML.
ParametroTipoDescrizione
data? String L'XML.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Imposta Content-Type: text/xml e il body. Passa l'XML come stringa. Una richiesta GET diventa POST.

Body XML
RESTBuilder.url('https://soap.example.com/').xml('<request><id>100</id></request>').callback(console.log);
method

builder.raw(value, [type])

Imposta il body così com'è.
ParametroTipoDescrizione
value String|Buffer Il body.
type? String Il tipo di contenuto breve.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Imposta il body senza alcuna serializzazione. type è uno dei tipi brevi di REQUEST() ('json', 'urlencoded', 'xml', 'html', 'plain', 'raw'); senza di esso imposta l'header con builder.type(). Una stringa viene inviata invariata. Un Buffer richiede il tipo 'raw' (application/octet-stream); senza tipo viene serializzato come JSON come un oggetto.

Body binario
RESTBuilder.url('https://api.example.com/images/').post().raw(buffer, 'raw').callback(console.log);
method

builder.text(value)

Invia testo semplice e lascia la risposta non analizzata.
ParametroTipoDescrizione
value String Il testo.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

builder.plain(value) è un alias. Imposta Content-Type: text/plain e il body, e la callback riceve il body grezzo della risposta invece di un valore analizzato.

Testo semplice
RESTBuilder.url('https://api.example.com/echo/').post().text('Hello').callback(function(err, response) {
	// response is the raw body
});
method

builder.file(name, filename, [source])

Aggiunge un file e invia una richiesta multipart.
ParametroTipoDescrizione
name String Il nome del campo del form.
filename String Il nome del file inviato al servizio.
source? Buffer|String Un buffer, un percorso o un URL.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

La richiesta diventa multipart/form-data (una GET diventa POST). source è un Buffer, un percorso su disco o un URL che viene scaricato e trasmesso in streaming. Senza source il file viene letto da filename. Il body impostato con json() o urlencoded() viene inviato come campi aggiuntivi del form quando è un oggetto.

Caricare due file
RESTBuilder.POST('https://files.example.com/upload/')
	.file('photo', 'photo.jpg', PATH.tmp('photo.jpg'))
	.file('logo', 'logo.png', 'https://cdn.example.com/logo.png')
	.callback(console.log);
method

builder.header(name, value)

Imposta un header della richiesta.
ParametroTipoDescrizione
name String Il nome dell'header.
value String Il valore.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Imposta un header. Helper per gli header comuni: builder.referrer(url) (alias referer()) imposta Referer, builder.origin(url) imposta Origin, builder.csrf(token) imposta X-Csrf-Token e builder.xhr() aggiunge X-Requested-With: XMLHttpRequest.

Header
builder.header('X-Token', CONF.apitoken).origin('https://www.example.com').xhr();
method

builder.type(value)

Imposta l'header Content-Type.
ParametroTipoDescrizione
value String Il tipo MIME.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Imposta Content-Type a un tipo MIME completo. Un tipo impostato da json(), urlencoded(), xml() o text() lo sostituisce, quindi usalo con raw(value).

Tipo personalizzato
builder.raw('{"id":1}').type('application/vnd.api+json');
method

builder.accept(ext)

Imposta l'header Accept.
ParametroTipoDescrizione
ext String Un'estensione o un tipo MIME.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Accetta un'estensione di file ('json', 'xml', 'html'...) e la converte nel suo tipo MIME; un valore più lungo viene usato così com'è.

Accettare XML
builder.accept('xml');
method

builder.auth(user, [password])

Imposta l'header Authorization.
ParametroTipoDescrizione
user String Il nome utente o l'intero valore dell'header.
password? String La password.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Con user e password imposta l'autenticazione basic (Basic base64(user:password)). Con un solo argomento il valore viene usato così com'è, ad esempio 'Bearer TOKEN'.

Basic e Bearer
builder.auth('admin', 'secret');
builder.auth('Bearer ' + CONF.apitoken);
method

builder.cookie(name, value)

Aggiunge un cookie alla richiesta.
ParametroTipoDescrizione
name String Il nome del cookie.
value String Il valore.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Aggiunge un cookie. builder.cookies(obj) sostituisce tutti i cookie con un oggetto { name: value }.

Cookie
builder.cookie('session', token);
builder.cookies({ lang: 'en', theme: 'dark' });
method

builder.cook([value])

Conserva i cookie della risposta nel builder.
ParametroTipoDescrizione
value? Boolean false lo disattiva. Predefinito: true

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Con cook() i cookie impostati dalla risposta vengono memorizzati nel builder e inviati con la richiesta successiva effettuata dallo stesso builder. output.cookies li contiene allora. cook(false) lo disattiva.

Login, poi lettura
RESTBuilder.url('https://example.com/login/').cook().urlencoded({ name: 'peter', password: 'x' }).callback(function(err, response, output) {
	RESTBuilder.GET('https://example.com/profile/').cookies(output.cookies).callback(console.log);
});
method

builder.timeout(ms)

Imposta il timeout.
ParametroTipoDescrizione
ms Number Millisecondi.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Il timeout in millisecondi (10000 per impostazione predefinita). 0 lo disattiva. Quando scade l'errore è 408: Request Timeout.

Cinque secondi
builder.timeout(5000);
method

builder.keepalive([val])

Riutilizza le connessioni con un agent keep-alive.
ParametroTipoDescrizione
val? Boolean Attiva o disattiva il keep-alive. Predefinito: true

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Senza argomento (o con un valore truthy) la richiesta usa l'agent keep-alive condiviso del framework, così le connessioni verso lo stesso host vengono riutilizzate. keepalive(false) lo disattiva. Non viene usato insieme a un proxy.

Keep-alive
RESTBuilder.GET('https://api.example.com/ping/').keepalive().callback(console.log);
method

builder.proxy(url)

Invia la richiesta attraverso un proxy.
ParametroTipoDescrizione
url String Il proxy.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

url è 'host:port' o 'http://host:port'. Con http://user:password@host:port le credenziali vengono inviate come Proxy-Authorization: Basic. Le destinazioni HTTPS vengono incapsulate in un tunnel con CONNECT. Senza di esso viene usato il proxy della chiave di configurazione $proxyrequest quando è impostata.

Proxy
builder.proxy('http://10.0.0.5:3128');
Proxy con login
builder.proxy('http://user:secret@10.0.0.5:3128');
method

builder.insecure()

Accetta certificati TLS non validi.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Accetta certificati autofirmati o scaduti del servizio. Usalo solo per servizi interni.

Autofirmato
RESTBuilder.GET('https://10.0.0.20/api/').insecure().callback(console.log);
method

builder.cert(key, cert, [dhparam])

Imposta un certificato TLS del client.
ParametroTipoDescrizione
key Buffer La chiave privata.
cert Buffer Il certificato.
dhparam? Buffer Parametri Diffie-Hellman.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Per i servizi che richiedono certificati client.

Certificato client
builder.cert(Total.Fs.readFileSync(PATH.root('client.key')), Total.Fs.readFileSync(PATH.root('client.crt')));
method

builder.unixsocket(socket, path)

Invia la richiesta attraverso un socket Unix.
ParametroTipoDescrizione
socket String Il file del socket.
path String Il percorso della richiesta, ad esempio /api/.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Si connette al file del socket invece che a un host; path è il percorso URL della richiesta.

API di Docker
RESTBuilder.make(function(builder) {
	builder.unixsocket('/var/run/docker.sock', '/containers/json');
	builder.callback(console.log);
});
method

builder.nodnscache()

Disattiva la cache DNS per questa richiesta.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Per impostazione predefinita il builder risolve l'hostname una volta e mette in cache i suoi indirizzi. Con nodnscache() Node.js lo risolve a ogni richiesta.

Senza cache DNS
builder.nodnscache();
method

builder.redirect(value)

Attiva o disattiva il seguire dei redirect.
ParametroTipoDescrizione
value Boolean false smette di seguire i redirect.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

redirect(false) restituisce la risposta 301 o 302 stessa; leggi la destinazione in output.headers.location. Per impostazione predefinita vengono seguiti fino a quattro redirect.

Leggere la location
RESTBuilder.GET('https://example.com/short/abc').redirect(false).callback(function(err, response, output) {
	console.log(output.status, output.headers.location);
});
method

builder.encrypt(key)

Cifra il corpo e decifra la risposta.
ParametroTipoDescrizione
key String La chiave di cifratura.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Il body viene cifrato con key e inviato con l'header X-Encryption: a; una risposta di testo viene decifrata con la stessa chiave. Entrambe le parti devono usare la stessa chiave.

Chiamata cifrata
builder.encrypt(CONF.sharedkey);
method

builder.progress(fn)

Riporta l'avanzamento del download.
ParametroTipoDescrizione
fn Function function(percentage).

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Chiama fn(percentage) per ogni chunk ricevuto. La percentuale è nota solo quando la risposta ha Content-Length, altrimenti è 0.

Avanzamento
builder.progress(function(percentage) {
	console.log(percentage.toFixed(1) + '%');
});
method

builder.noparse()

Restituisce il body grezzo della risposta.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

La callback riceve il body come stringa (o un Buffer per i tipi binari) invece di un valore analizzato.

HTML grezzo
RESTBuilder.GET('https://example.com/').noparse().callback(function(err, html) {
	console.log(html.length);
});
method

builder.base64()

Restituisce il body della risposta in base64.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

La callback riceve il body codificato in base64, ad esempio per incorporare un'immagine come data URI.

Data URI
RESTBuilder.GET('https://cdn.example.com/logo.png').base64().callback(function(err, data) {
	var uri = 'data:image/png;base64,' + data;
});
method

builder.debug()

Stampa la richiesta e la risposta nella console.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Dopo l'arrivo della risposta stampa lo stato, il metodo, l'URL con la query, l'errore e il body grezzo.

Debug
RESTBuilder.GET('https://api.example.com/products/').debug().callback(NOOP);
method

builder.callback([fn])

Invia la richiesta e riceve la risposta analizzata.
ParametroTipoDescrizione
fn? Function|Object function(err, response, output) o il $ di un'azione.

Restituisce RESTBuilder|Promise Il builder, oppure una promise quando viene chiamato senza argomento.

Invia la richiesta al tick successivo e passa il risultato a fn(err, response, output):

  • response: il body interpretato in base al suo Content-Type (JSON, anche per text/plain; URL-encoded; XML tramite il parser HTML; gli altri body vengono interpretati come JSON quando sembrano JSON). Un body vuoto produce un oggetto vuoto; una risposta 204 produce true.
  • output: status, headers, response (il body grezzo), hostname, origin, cookies (con cook()) e output.cookie(name), che legge un cookie della risposta.
  • err: l'errore di rete o '408: Request Timeout'; un ErrorBuilder quando il body è un array di errori Total.js ([{ error: '...' }], e allora response è null); altrimenti, per uno stato 400 o superiore, un ErrorBuilder con un errore il cui nome è il codice di stato e il cui messaggio è il body grezzo. Un valore impostato con builder.error() sostituisce qualsiasi errore.

fn può essere anche il $ di un'azione: la risposta interpretata viene passata a $.callback() e un errore viene aggiunto agli errori di $. Senza argomento restituisce una promise che si risolve con response e viene rifiutata con err.

Callback
RESTBuilder.GET('https://api.example.com/products/').callback(function(err, response, output) {
	if (err)
		return console.log(err);
	console.log(output.status, response.length);
});
In un'azione
NEWACTION('Products/sync', {
	name: 'Sync products',
	action: function($) {
		RESTBuilder.GET(CONF.shopapi + '/products/').callback($);
	}
});
method

builder.promise([$])

Invia la richiesta e restituisce una promise.
ParametroTipoDescrizione
$? Object Il $ di un'azione.

Restituisce Promise Si risolve con la risposta analizzata.

La promise si risolve con la risposta analizzata. In caso di errore viene rifiutata con un Error creato dall'errore (un ErrorBuilder diventa un Error con i suoi messaggi). Con $ l'errore va invece a $.invalid() e la promise non viene rifiutata.

await
var user = await RESTBuilder.GET('https://api.example.com/users/100/').promise();
Con $
var order = await RESTBuilder.POST(CONF.shopapi + '/orders/', model).promise($);
method

builder.exec([callback])

Invia subito la richiesta.
ParametroTipoDescrizione
callback? Function function(err, response, output).

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Invia la richiesta immediatamente e chiama callback(err, response, output) con gli stessi valori di callback(). Preferisci callback(), che attende il tick successivo. Quando callback è omessa il risultato viene ignorato.

Exec
RESTBuilder.GET('https://api.example.com/ping/').exec(function(err, response) {
	console.log(err, response);
});
method

builder.stream(callback)

Restituisce la risposta come stream.
ParametroTipoDescrizione
callback Function function(err, response).

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Invia la richiesta al tick successivo e chiama callback(err, response) non appena arrivano gli header. response ha status, headers, origin e stream (la risposta Node.js, non ancora letta). Usalo per i file di grandi dimensioni.

Salvare un file di grandi dimensioni
RESTBuilder.GET('https://cdn.example.com/backup.zip').stream(function(err, response) {
	if (!err && response.status === 200)
		response.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('backup.zip')));
});
method

builder.error(value)

da 0.0.16 Sostituisce qualsiasi errore con un tuo valore.
ParametroTipoDescrizione
value Object|String L'errore da restituire, per esempio un messaggio o un ErrorBuilder.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Quando la richiesta termina con un errore qualsiasi (di rete, di timeout o uno stato 400 o superiore), la callback o la promise ricevono invece value. Usalo per nascondere ai tuoi utenti i dettagli di un servizio remoto.

Errore personalizzato
RESTBuilder.GET(CONF.stockapi).error('The stock service is not available').callback($);
method

builder.logerror()

da 0.0.16 Stampa gli errori nella console.

Restituisce RESTBuilder Lo stesso builder, per il concatenamento.

Quando la richiesta termina con un errore, l'errore (o il body grezzo della risposta) viene passato al gestore degli errori del framework, che lo stampa con il nome RESTBuilder e il metodo e l'URL della richiesta. La callback riceve comunque l'errore.

Registrare gli errori
RESTBuilder.POST(CONF.crmapi + '/contacts/', model).logerror().callback($);
Fatto in Europa