ForgeTotal.js 5
it

Total.js 5

Chiamare altre API HTTP con RESTBuilder

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

RESTBuilder.GET(url), .POST(url, data), .PUT, .PATCH e .DELETE costruiscono una richiesta. I dati di un POST vengono inviati come JSON. Concatena .header(name, value), .cookie(name, value), .timeout(milliseconds) e .auth(user, password) prima di .exec(function(err, response, output) {}) (o .promise() per await).

  • response è il body, interpretato automaticamente quando è JSON
  • output.status è lo stato HTTP e output.headers gli header della risposta
  • err è valorizzato per errori di rete e per stati HTTP di errore

L'esempio chiama due route della propria app per poter girare ovunque; nel tuo codice usa l'indirizzo del servizio reale. $.hostname(path) costruisce l'URL completo di questo server.

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