ForgeTotal.js 5
es

Total.js 5

Llama a otros servidores con REQUEST y guarda archivos con DOWNLOAD

Total.js 5 · total5@0.0.19 httprequestdownload Ejecutada con Total.js 5

REQUEST(options) es el cliente HTTP de bajo nivel sobre el que está construido RESTBuilder. Pásale un objeto y haz await (o dale un callback como segundo argumento). Las opciones más útiles son url, method (por defecto GET), query (un objeto que se añade a la URL), headers, cookies, body (una cadena o un Buffer), type (json, text, html, xml, urlencoded o raw, que establece el content-type), timeout en milisegundos y noredirect.

El resultado es un objeto con status, headers, cookies y body (una cadena; interpreta el JSON tú mismo con .parseJSON()). Una respuesta con un estado de error como 404 no es un error: comprueba status. La promesa solo se rechaza cuando falla la propia petición (conexión rechazada, timeout, host no válido).

DOWNLOAD(url, filename) vuelca la respuesta en un archivo y se resuelve con { status, size, filename }. No mira el estado, así que compruébalo antes de usar el archivo.

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 });
}