Spanish Total.js
English
Documentation For AI agents
Contents

HTTP requests

Call other HTTP services with RESTBuilder, REQUEST(), AJAX() and DOWNLOAD().

.md GitHub
On this page

Total.js has four tools for calling other HTTP services from your application: RESTBuilder for REST APIs, REQUEST() for full control of a single request, AJAX() for a quick JSON call and DOWNLOAD() for saving a remote file. OPENCLIENT() keeps a WebSocket connection to another service for request-response messages. All of them are global, so you call them in actions, schemas, plugins and definitions without require().

RESTBuilder

RESTBuilder builds a request step by step and parses the response for you. The static helpers create a builder with the method and the data already set:

RESTBuilder.GET('https://api.example.com/products/', { page: 1 }).callback(function(err, response, output) {
    // response: the parsed JSON body
    // output.status, output.headers
    console.log(err, response);
});

RESTBuilder.POST('https://api.example.com/orders/', { productid: 'p100', count: 2 }).callback(console.log);

GET() sends the data as a query string. POST(), PUT(), PATCH() and DELETE() send it as a JSON body. You can also start with RESTBuilder.url(url) or RESTBuilder.make(fn) and set everything with methods:

RESTBuilder.make(function(builder) {
    builder.url('https://api.example.com/users/');
    builder.auth('Bearer ' + CONF.apitoken);
    builder.header('X-Client', 'shop');
    builder.timeout(5000);
    builder.json({ name: 'Peter', email: 'peter@example.com' });
    builder.callback(function(err, response) {
        console.log(err, response);
    });
});

The request is sent on the next tick after callback() or stream(), so the order of the other methods does not matter. promise() sends it at once, so call it last.

The response

The callback receives (err, response, output). response is the body parsed by its Content-Type: JSON (also text/plain and unknown types that contain JSON), URL-encoded data, or XML (parsed with the HTML parser). An empty body gives an empty object. output holds status, headers, response (the raw body), hostname, origin and the method output.cookie(name).

err is set when the connection fails, when the timeout expires, or when the status code is 400 or more. For a status error err is an ErrorBuilder: with the errors of a Total.js error array ([{ error: '...' }]), or with one error whose name is the status code and whose message is the raw response body.

error(value) replaces any error with your own value, and logerror() prints errors to the console through the framework error handler:

RESTBuilder.GET('https://api.example.com/stock/')
    .logerror()
    .error('The stock service is not available')
    .callback(function(err, response) {
        // err === 'The stock service is not available' on any error
    });

Promises

promise() returns a promise that resolves with the parsed body and rejects with an Error. callback() without a function also returns a promise. Pass the $ of an action to promise($) and an error goes straight to $.invalid(); callback($) passes the whole result to $.callback():

NEWACTION('Orders/create', {
    name: 'Create an order',
    input: '*productid:String, *count:Number',
    action: async function($, model) {
        var order = await RESTBuilder.POST(CONF.shopapi + '/orders/', model).promise($);
        $.callback(order);
    }
});

Bodies, files and headers

json(data), urlencoded(data) and xml(text) set the body and its type (a GET request becomes POST). raw(value, [type]) sends a string as it is, or a buffer with raw(buffer, 'raw'). text(value) sends plain text and also returns the response body without parsing. file(name, filename, [buffer|path|url]) adds a file and sends the request as multipart/form-data:

RESTBuilder.POST('https://files.example.com/upload/')
    .file('file', 'invoice.pdf', PATH.databases('invoice.pdf'))
    .callback(console.log);

header(name, value), type(contentType), accept(ext), auth(user, [password]), cookie(name, value), referrer(url), origin(url), csrf(token) and xhr() set headers. cook() keeps the cookies of the response in the builder, so the next request with the same builder sends them back.

Connection options

timeout(ms) (10 seconds by default), keepalive([val]), proxy(url), insecure() for self-signed certificates, cert(key, cert, [dhparam]) for client certificates, unixsocket(socket, path), nodnscache() and redirect(false) control how the request is made. By default the builder caches DNS lookups and follows up to four redirects.

Streams and progress

stream(callback) gives you the response as a stream, without reading the body. progress(fn) reports the download percentage when the service sends Content-Length:

RESTBuilder.GET('https://cdn.example.com/backup.zip').stream(function(err, response) {
    if (err)
        return;
    response.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('backup.zip')));
});

Total.js APIs

RESTBuilder.API(url, name, [data]) calls an API endpoint of another Total.js application (a route API /api/ ...). It sends { schema: name, data: data } as JSON:

RESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).callback(console.log);

The request stays a POST: get(query) adds the query to the body ({ schema, data, query }), and compress() leaves out the keys with null or undefined values:

RESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes', color: null }).get({ page: 2 }).compress().callback(console.log);
// body: { data: { category: 'shoes' }, query: { page: 2 }, schema: 'products_list' }

REQUEST()

REQUEST(options, [callback]) is the low-level function used by all the tools above. You describe the whole request in one object. The callback receives (err, response); without a callback it returns a promise.

REQUEST({
    url: 'https://api.example.com/status/',
    method: 'POST',
    type: 'json',
    body: JSON.stringify({ ping: 1 }),
    headers: { 'X-Token': CONF.apitoken },
    timeout: 5000,
    keepalive: true
}, function(err, response) {
    // response.status, response.headers, response.body (a string)
    console.log(err, response.status, response.body);
});

REQUEST() does not parse the body: response.body is a string for text and application types and a Buffer for other types. The default timeout is 8 seconds (timeout: 0 disables it). With custom: true the callback receives response.stream instead of the body. With writer: function(req) {} you write the body yourself and end the request with req.end(). The full list of options is in the reference.

All outgoing requests can go through one proxy with the configuration key $proxyrequest (see Configuration); requests to localhost skip it. Credentials in a URL are sent for you: https://user:password@host/ as Authorization: Basic, and a proxy http://user:password@host:port as Proxy-Authorization: Basic.

AJAX()

AJAX('METHOD url', [data], [callback]) is the shortest way to call a JSON service. data is sent as JSON and the response is parsed by its type: JSON, URL-encoded data and XML become objects. For a status of 400 or more the error is the parsed body; the promise turns a Total.js error array into an Error.

AJAX('POST https://api.example.com/login/', { email: 'peter@example.com' }, function(err, response) {
    console.log(err, response);
});

var products = await AJAX('GET https://api.example.com/products/');

DOWNLOAD()

DOWNLOAD(url, filename, [callback], [timeout]) saves a remote file to disk. Total.download() is the same function. response.size is the number of bytes saved. Check response.status, because the body is saved for every status code:

DOWNLOAD('https://cdn.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {
    if (!err && response.status === 200)
        console.log('Saved', response.size, 'bytes to', response.filename);
});
Made in Europe