Apelează alte servere cu REQUEST și salvează fișiere cu DOWNLOAD
REQUEST(options) este clientul HTTP de nivel scăzut pe care este construit RESTBuilder. Dă-i un obiect și folosește await (sau dă-i un callback ca al doilea argument). Opțiunile utile sunt url, method (implicit GET), query (un obiect, adăugat la URL), headers, cookies, body (un șir sau un Buffer), type (json, text, html, xml, urlencoded sau raw, care setează content-type), timeout în milisecunde și noredirect.
Rezultatul este un obiect cu status, headers, cookies și body (un șir; interpretează singur JSON-ul cu .parseJSON()). Un răspuns cu o stare de eroare precum 404 nu este o eroare: verifică status. Promisiunea este respinsă doar când eșuează cererea însăși (conexiune refuzată, timeout, host invalid).
DOWNLOAD(url, filename) transmite răspunsul într-un fișier și se rezolvă cu { status, size, filename }. Nu se uită la stare, așa că verific-o înainte de a folosi fișierul.
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 });
}