ForgeTotal.js 5
pl

Total.js 5

Wywołuj inne serwery przez REQUEST i zapisuj pliki przez DOWNLOAD

Total.js 5 · total5@0.0.19 httprequestdownload Uruchomiono z Total.js 5

REQUEST(options) to niskopoziomowy klient HTTP, na którym zbudowany jest RESTBuilder. Przekaż mu obiekt i użyj await (albo podaj callback jako drugi argument). Przydatne opcje to url, method (domyślnie GET), query (obiekt dołączany do URL), headers, cookies, body (ciąg znaków lub Buffer), type (json, text, html, xml, urlencoded lub raw, co ustawia content-type), timeout w milisekundach i noredirect.

Wynik to obiekt z status, headers, cookies i body (ciąg znaków; JSON przetwórz sam przez .parseJSON()). Odpowiedź ze statusem błędu, takim jak 404, nie jest błędem: sprawdź status. Obietnica jest odrzucana tylko wtedy, gdy zawiedzie samo żądanie (odmowa połączenia, timeout, nieprawidłowy host).

DOWNLOAD(url, filename) strumieniuje odpowiedź do pliku i rozwiązuje się z { status, size, filename }. Nie patrzy na status, więc sprawdź go przed użyciem pliku.

controllers/request.js
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 });
}