Chiamare altri server con REQUEST e salvare file con DOWNLOAD
REQUEST(options) è il client HTTP di basso livello su cui è costruito RESTBuilder. Passagli un oggetto e usa await (oppure dagli una callback come secondo argomento). Le opzioni utili sono url, method (predefinito GET), query (un oggetto, aggiunto all'URL), headers, cookies, body (una stringa o un Buffer), type (json, text, html, xml, urlencoded o raw, che imposta content-type), timeout in millisecondi e noredirect.
Il risultato è un oggetto con status, headers, cookies e body (una stringa; interpreta il JSON da solo con .parseJSON()). Una risposta con uno stato di errore come 404 non è un errore: controlla status. La promise viene rifiutata solo quando fallisce la richiesta stessa (connessione rifiutata, timeout, host non valido).
DOWNLOAD(url, filename) scrive la risposta in streaming in un file e si risolve con { status, size, filename }. Non guarda lo stato, quindi controllalo prima di usare il file.
exports.install = function() {
ROUTE('GET /remote/', remote);
ROUTE('POST /remote/ @json', remote_post);
ROUTE('GET /remote/text/', remote_text);
ROUTE('GET /call/', call);
ROUTE('GET /download/', download);
};
function remote($) {
$.json({ hello: 'world', name: $.query.name || null });
}
function remote_post($) {
$.json({ received: $.body, token: $.headers['x-token'] || null });
}
function remote_text($) {
$.plain('first line\nsecond line\n');
}
async function call($) {
var get = await REQUEST({ url: $.hostname('/remote/'), query: { name: 'Louis' } });
var post = await REQUEST({ method: 'POST', url: $.hostname('/remote/'), type: 'json', body: JSON.stringify({ a: 1 }), headers: { 'x-token': 'abc' } });
var missing = await REQUEST({ url: $.hostname('/does-not-exist/') });
var failed = null;
try {
await REQUEST({ url: 'http://127.0.0.1:1/' });
} catch (e) {
failed = true;
}
$.json({
get: get.body.parseJSON(),
post: post.body.parseJSON(),
status: [get.status, missing.status],
failed: failed
});
}
async function download($) {
var filename = PATH.tmp('forge-download.txt');
var response = await DOWNLOAD($.hostname('/remote/text/'), filename);
var content = require('fs').readFileSync(filename).toString('utf8');
$.json({ status: response.status, size: response.size, content: content });
}