Chiamare altre API HTTP con RESTBuilder
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 è JSONoutput.statusè lo stato HTTP eoutput.headersgli header della rispostaerrè 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.
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 });
});
}