ForgeTotal.js 5
sk

Total.js 5

Volaj iné HTTP API cez RESTBuilder

Total.js 5 · total5@0.0.19 integrationshttprestbuilder Spustené s Total.js 5

RESTBuilder.GET(url), .POST(url, data), .PUT, .PATCH a .DELETE zostavia požiadavku. Dáta POST sa posielajú ako JSON. Reťaz .header(name, value), .cookie(name, value), .timeout(milliseconds) a .auth(user, password) pred .exec(function(err, response, output) {}) (alebo .promise() pre await).

  • response je telo, automaticky spracované, ak je to JSON
  • output.status je HTTP stav a output.headers hlavičky odpovede
  • err je nastavené pri sieťových chybách aj pri chybových HTTP stavoch

Príklad volá dve cesty vlastnej aplikácie, aby bežal kdekoľvek; vo svojom kóde použi adresu skutočnej služby. $.hostname(path) zostaví úplnú URL tohto servera.

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