ForgeTotal.js 5
es

Total.js 5

Llama a otras APIs HTTP con RESTBuilder

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

RESTBuilder.GET(url), .POST(url, data), .PUT, .PATCH y .DELETE construyen una petición. Los datos de un POST se envían como JSON. Encadena .header(name, value), .cookie(name, value), .timeout(milliseconds) y .auth(user, password) antes de .exec(function(err, response, output) {}) (o .promise() para await).

  • response es el body, interpretado automáticamente cuando es JSON
  • output.status es el estado HTTP y output.headers las cabeceras de la respuesta
  • err se rellena en errores de red y en estados HTTP de error

El ejemplo llama a dos rutas de su propia app para poder ejecutarse en cualquier sitio; en tu código usa la dirección del servicio real. $.hostname(path) construye la URL completa de este servidor.

controllers/service.js
exports.install = function() {
	ROUTE('GET /api/hello/', hello);
	ROUTE('POST /api/sum/', sum);
	ROUTE('GET /call/', call);
};

function hello($) {
	$.json({ message: 'hello', agent: $.headers['x-agent'] || null });
}

function sum($) {
	$.json({ sum: $.body.a + $.body.b });
}

async function call($) {

	var greeting = await RESTBuilder.GET($.hostname('/api/hello/')).header('x-agent', 'forge').timeout(5000).promise();
	var total = await RESTBuilder.POST($.hostname('/api/sum/'), { a: 20, b: 22 }).promise();

	RESTBuilder.GET($.hostname('/api/missing/')).exec(function(err, response, output) {
		$.json({ greeting: greeting, total: total, missing: output.status });
	});
}