Más szerverek hívása REQUEST-tel és fájlok mentése DOWNLOAD-dal
A REQUEST(options) az alacsony szintű HTTP-kliens, amelyre a RESTBuilder épül. Adj neki egy objektumot, és használj await-et (vagy adj neki callbacket második argumentumként). A hasznos opciók: url, method (alapértelmezés szerint GET), query (egy objektum, amely az URL-hez fűződik), headers, cookies, body (szöveg vagy Buffer), type (json, text, html, xml, urlencoded vagy raw, ami a content-type-ot állítja), timeout ezredmásodpercben és noredirect.
Az eredmény egy objektum status, headers, cookies és body mezőkkel (szöveg; a JSON-t magad dolgozd fel a .parseJSON()-nal). Egy hibaállapotú válasz, például 404, nem hiba: ellenőrizd a status-t. A promise csak akkor utasítódik el, ha maga a kérés hibázik (elutasított kapcsolat, időtúllépés, érvénytelen host).
A DOWNLOAD(url, filename) fájlba streameli a választ, és { status, size, filename } értékkel teljesül. Nem nézi az állapotot, ezért a fájl használata előtt ellenőrizd.
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 });
}