Llama a otras APIs HTTP con RESTBuilder
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).
responsees el body, interpretado automáticamente cuando es JSONoutput.statuses el estado HTTP youtput.headerslas cabeceras de la respuestaerrse 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.
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 });
});
}