Spanish Total.js
English
Documentation For AI agents
Contents

HTTP requests

RESTBuilder, REQUEST(), AJAX(), DOWNLOAD() and Total.download().

.md GitHub
On this page

The global functions and the RESTBuilder class for HTTP requests to other services. For an introduction with examples read the guide HTTP requests. The WebSocket client OPENCLIENT() has its own page: OpenClient.

API

method

REQUEST(options, [callback])

Sends an HTTP request with full control of the options.
ParameterTypeDescription
options.url String The URL of the request. Credentials in the URL (https://user:password@host/) are sent as Authorization: Basic; percent-encoded characters in them are decoded first.
options.method? String The HTTP method in upper case. Default: 'GET'
options.headers? Object Request headers. The object is copied, so your object is not changed.
options.type? String Sets Content-Type: 'json', 'urlencoded', 'xml', 'html', 'plain' or 'text', 'raw' (application/octet-stream).
options.body? String|Buffer The request body. A string is sent as UTF-8; Content-Length is set for you.
options.query? Object|String Appended to the URL as a query string.
options.cookies? Object Cookies to send, as { name: value }.
options.cook? Boolean Stores the cookies of the response into options.cookies, so the same options object sends them with the next request.
options.timeout? Number Timeout in milliseconds; 0 disables it. Default: 8000
options.encoding? String Encoding of a text body. 'binary' returns a Buffer. Default: 'utf8'
options.xhr? Boolean Adds X-Requested-With: XMLHttpRequest.
options.files? Array Files for a multipart/form-data request: [{ name, filename, buffer | path | url }]. options.body is then an object of extra form fields.
options.compress? String Compresses the body: 'gzip' or 'deflate', and sets Content-Encoding.
options.encrypt? String A key: the body is encrypted with it and the text response is decrypted with it.
options.writer? Function function(req) writes the body itself: it gets the Node.js request, writes the data and calls req.end(). body and files are then not used.
options.custom? Boolean Returns response.stream instead of reading the body.
options.noredirect? Boolean Does not follow redirects; the callback gets the 301/302 response.
options.keepalive? Boolean Uses a shared keep-alive agent (one for HTTP, one for HTTPS).
options.resolve? Boolean Resolves the hostname with a DNS cache. options.dnscache does the same. Skipped for localhost and IP addresses.
options.proxy? String A proxy for this request, as 'host:port' or 'http://host:port'. With http://user:password@host:port the credentials are sent as Proxy-Authorization: Basic.
options.insecure? Boolean Accepts invalid or self-signed TLS certificates.
options.key? Buffer Client TLS key.
options.cert? Buffer Client TLS certificate.
options.dhparam? Buffer TLS Diffie-Hellman parameters.
options.unixsocket? Object { socket, path } to send the request through a Unix socket instead of url.
options.ondata? Function function(chunk, percentage) for every received chunk.
options.onprogress? Function function(percentage); the percentage is known only with Content-Length.
options.callback? Function function(err, response), instead of the second argument.
callback? Function function(err, response).

Returns Promise A promise when no callback is given; otherwise nothing.

Sends one HTTP request described by options. The callback receives (err, response); without a callback (in the argument or in options.callback) it returns a promise that resolves with response.

The response object has status, headers, body, host, origin (the resolved IP addresses when DNS caching is on) and cookies (the cookies collected on redirects). body is a string for text/* and application/* types (decoded with encoding) and a Buffer for the other types, or always a Buffer with encoding: 'binary'. The body is not parsed: use RESTBuilder or AJAX() for that.

With custom: true the callback runs as soon as the headers arrive and the response has stream (the Node.js response) instead of body.

Errors: a network error passes the error object with response.status === 0; an expired timeout passes '408: Request Timeout' with response.status === 408; more than four redirects pass 'Too many redirects'; a URL without a hostname passes 'Invalid hostname', and a string that is not a URL throws TypeError: Invalid URL. A status code of 400 or more is not an error: check response.status.

Redirects 301 and 302 are followed (cookies of the redirect are sent to the next location). Requests use the proxy of the configuration key $proxyrequest when it is set, except for localhost, 127.0.0.1 and 0.0.0.0.

POST JSON
REQUEST({
	url: 'https://api.example.com/orders/',
	method: 'POST',
	type: 'json',
	body: JSON.stringify({ id: 'p100', count: 2 })
}, function(err, response) {
	if (err || response.status !== 200)
		return;
	var order = response.body.parseJSON();
});
With a promise
var response = await REQUEST({ url: 'https://example.com/robots.txt', timeout: 3000 });
console.log(response.status, response.body);
Upload a file
REQUEST({
	url: 'https://files.example.com/upload/',
	method: 'POST',
	files: [{ name: 'file', filename: 'report.pdf', path: PATH.databases('report.pdf') }],
	body: { folder: 'reports' }
}, console.log);
Read a stream
REQUEST({ url: 'https://cdn.example.com/video.mp4', custom: true }, function(err, response) {
	if (!err)
		response.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('video.mp4')));
});
Write the body yourself
REQUEST({
	url: 'https://api.example.com/import/',
	method: 'POST',
	type: 'plain',
	writer: function(req) {
		for (var line of lines)
			req.write(line + '\n');
		req.end();
	}
}, console.log);
method

AJAX('METHOD url', [data], [callback])

Sends a JSON request and returns the parsed response.
ParameterTypeDescription
url String 'METHOD url', for example 'POST [https://example.com/api/'](https://example.com/api/'`).
data? Object Data sent as JSON.
callback? Function function(err, response, meta).

Returns Promise A promise when no callback is given.

Sends a request and parses the response. The first argument is the method and the URL separated by a space; without a method it is GET. data is sent as a JSON body. The header X-Requested-With: XMLHttpRequest is always added.

The response is parsed by its Content-Type: JSON (application/json, text/json), URL-encoded data and XML (application/xml, text/xml) become objects; other types are returned as the raw body. An XML document becomes a flat object: the names of nested elements are joined with _ (order_name), repeated elements give an array, and the attributes of an element are in an object under its name with __ (order__). An empty XML body gives {}. The callback receives (err, response, meta) where meta has status, headers and host.

For a status of 400 or more err is the parsed body (for a Total.js service the error array) and response is null. Without a callback the function returns a promise that resolves with the parsed body and rejects with err; a Total.js error array becomes an Error whose message holds the error messages.

Callback
AJAX('POST https://api.example.com/login/', { email: 'peter@example.com' }, function(err, response, meta) {
	console.log(meta.status, response);
});
Promise
var products = await AJAX('GET https://api.example.com/products/?page=1');
XML answer
// the service answers <order id="100"><name>Book</name><items><item>A</item><item>B</item></items></order>
var order = await AJAX('GET https://api.example.com/orders/100/');
// { order__: { id: '100' }, order_name: 'Book', order_items_item: ['A', 'B'] }
method

DOWNLOAD(url, filename, [callback], [timeout])

Downloads a remote file to the disk.
ParameterTypeDescription
url String|Object The URL, or { socket, path } for a Unix socket.
filename String The target file path.
callback? Function function(err, response).
timeout? Number Timeout in milliseconds. Default: 8000

Returns Promise A promise when no callback is given.

Downloads url and writes the body to filename. The callback runs when the file is written, with (err, response). response has status, headers, origin, filename and size (the number of bytes written). The body is saved for every status code, so check response.status.

url can also be an object { socket, path } for a Unix socket. DNS lookups are cached. timeout is in milliseconds (8 seconds when not set). Without a callback the function returns a promise that resolves with response.

Download an image
DOWNLOAD('https://cdn.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {
	if (!err && response.status === 200)
		console.log('Saved', response.filename);
});
Promise
var response = await DOWNLOAD('https://example.com/data.csv', PATH.tmp('data.csv'));
method

Total.download(url, filename, [callback], [timeout])

The framework method behind DOWNLOAD().
ParameterTypeDescription
url String|Object The URL, or { socket, path } for a Unix socket.
filename String The target file path.
callback? Function function(err, response).
timeout? Number Timeout in milliseconds. Default: 8000

Returns Promise A promise when no callback is given.

The same function as DOWNLOAD(). Downloads url and writes the body to filename. The callback runs when the file is written, with (err, response). response has status, headers, origin, filename and size (the number of bytes written). The body is saved for every status code, so check response.status.

url can also be an object { socket, path } for a Unix socket. DNS lookups are cached. timeout is in milliseconds (8 seconds when not set). Without a callback the function returns a promise that resolves with response.

Download
Total.download('https://example.com/export.json', PATH.tmp('export.json'), function(err, response) {
	console.log(err, response.status);
});
class

new RESTBuilder([url])

A builder for requests to REST services.
ParameterTypeDescription
url? String The URL of the request.

Returns RESTBuilder A new builder.

A global class. A new builder has the method GET, a timeout of 10 seconds, DNS caching on, the header user-agent: Total.js/v... and accept: application/json, text/plain, text/plain, text/xml. Nothing is sent until you call callback(), promise(), stream() or exec().

You usually start with a static helper: RESTBuilder.GET(), POST(), PUT(), PATCH(), DELETE(), HEAD(), API(), url() or make(). RESTBuilder.url(url) is the same as new RESTBuilder(url).

Create a builder
var builder = RESTBuilder.url('https://api.example.com/users/');
builder.header('X-Token', CONF.apitoken);
builder.callback(console.log);
method

RESTBuilder.make(fn)

Creates a builder and passes it to a function.
ParameterTypeDescription
fn Function function(builder).

Returns RESTBuilder The new builder.

Creates a builder without a URL and calls fn(builder). Set the URL with builder.url(). The instance method builder.make(fn) calls fn with the builder as this and as the argument, for reusable settings.

Build a request
RESTBuilder.make(function(builder) {
	builder.url('https://api.example.com/users/');
	builder.post({ name: 'Peter' });
	builder.callback(console.log);
});
method

RESTBuilder.GET(url, [data])

Creates a GET request.
ParameterTypeDescription
url String The URL.
data? Object Sent as the query string.

Returns RESTBuilder A new builder.

Creates a builder with the method GET; data becomes the query string. For a HEAD request use RESTBuilder.HEAD(url): it has no data, the parsed value is an empty object and you read output.status and output.headers.

Query string
RESTBuilder.GET('https://api.example.com/products/', { page: 2, limit: 20 }).callback(function(err, response) {
	console.log(response);
});
HEAD
RESTBuilder.HEAD('https://example.com/').callback(function(err, response, output) {
	console.log(output.status, output.headers['last-modified']);
});
method

RESTBuilder.POST(url, [data])

Creates a POST request.
ParameterTypeDescription
url String The URL.
data? Object Sent as a JSON body.

Returns RESTBuilder A new builder.

Creates a builder with the method POST; data is sent as JSON. RESTBuilder.PUT(), RESTBuilder.PATCH() and RESTBuilder.DELETE() work the same way with their methods.

POST JSON
RESTBuilder.POST('https://api.example.com/orders/', { productid: 'p100', count: 2 }).promise().then(function(order) {
	console.log(order.id);
});
method

RESTBuilder.PUT(url, [data])

Creates a PUT request.
ParameterTypeDescription
url String The URL.
data? Object Sent as a JSON body.

Returns RESTBuilder A new builder.

Creates a builder with the method PUT; data is sent as JSON.

PUT
RESTBuilder.PUT('https://api.example.com/products/p100/', { price: 99 }).callback(console.log);
method

RESTBuilder.PATCH(url, [data])

Creates a PATCH request.
ParameterTypeDescription
url String The URL.
data? Object Sent as a JSON body.

Returns RESTBuilder A new builder.

Creates a builder with the method PATCH; data is sent as JSON.

PATCH
RESTBuilder.PATCH('https://api.example.com/products/p100/', { price: 99 }).callback(console.log);
method

RESTBuilder.DELETE(url, [data])

Creates a DELETE request.
ParameterTypeDescription
url String The URL.
data? Object Sent as a JSON body.

Returns RESTBuilder A new builder.

Creates a builder with the method DELETE; data is sent as JSON.

DELETE
RESTBuilder.DELETE('https://api.example.com/products/p100/').callback(console.log);
method

RESTBuilder.API(url, name, [data])

Calls an API endpoint of a Total.js application.
ParameterTypeDescription
url String The URL of the API endpoint.
name String The name of the API operation.
data? Object The data of the operation.

Returns RESTBuilder A new builder.

Creates a POST request for a Total.js API route (ROUTE('API /api/ ...')). The body is JSON: { schema: name, data: data }. name is the API name with optional parameters, for example 'products_detail/p100'. builder.get(query) keeps the POST and sends the query in the body as query, next to data. builder.compress() leaves out the keys of the body whose value is null or undefined.

Call an API
RESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).callback(function(err, response) {
	console.log(err, response);
});
With a query
RESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).get({ page: 2 }).callback(console.log);
// body: { data: { category: 'shoes' }, query: { page: 2 }, schema: 'products_list' }
method

builder.compress([value])

Leaves out empty values from the body of a RESTBuilder.API() request.
ParameterTypeDescription
value? Boolean false turns it off. Default: true

Returns RESTBuilder The same builder, for chaining.

Without an argument or with true, the JSON body of a RESTBuilder.API() request is written without the keys whose value is null or undefined, so the request is smaller. compress(false) turns it off. Other builders are not affected.

Smaller body
RESTBuilder.API(CONF.erpapi, 'orders_save', { id: 'A1', note: null, total: 120 }).compress().callback(console.log);
// data: { id: 'A1', total: 120 }
method

RESTBuilder.upgrade(fn)

Registers a function that changes every builder before it is sent.
ParameterTypeDescription
fn Function function(builder).

The function runs for every builder in the application just before the request is made, with the builder as the argument. Use it for shared headers or tokens. Upgrades cannot be removed.

Add a token to one service
RESTBuilder.upgrade(function(builder) {
	if (builder.url().startsWith(CONF.shopapi))
		builder.header('X-Token', CONF.shoptoken);
});
method

builder.url([url])

Sets or reads the URL.
ParameterTypeDescription
url? String The new URL.

Returns RESTBuilder|String The builder, or the URL when called without an argument.

With an argument sets the URL and returns the builder; without one returns the current URL.

Read the URL
var url = builder.url();
method

builder.method(method, [data])

Sets the HTTP method.
ParameterTypeDescription
method String The HTTP method.
data? Object Data sent as JSON.

Returns RESTBuilder The same builder, for chaining.

Sets the method (lower case is converted to upper case). data is sent as JSON.

Shortcuts: builder.get([query]) sets GET and the query string; builder.post([data]), builder.put([data]), builder.patch([data]) and builder.delete([data]) set the method and the body (in the type set before, JSON by default); builder.head() sets HEAD. Upper-case names (builder.POST()) are aliases.

Shortcuts
RESTBuilder.url('https://api.example.com/products/p100/').put({ price: 99 }).callback(console.log);
method

builder.json([data])

Sends data as JSON.
ParameterTypeDescription
data? Object The data.

Returns RESTBuilder The same builder, for chaining.

Sets the type to JSON and the body to data (an object is serialized when the request is sent). A GET request becomes POST.

JSON body
RESTBuilder.url('https://api.example.com/users/').json({ name: 'Peter' }).callback(console.log);
method

builder.urlencoded([data])

Sends data as a URL-encoded form.
ParameterTypeDescription
data? Object The form fields.

Returns RESTBuilder The same builder, for chaining.

Sets Content-Type: application/x-www-form-urlencoded and the body; an object is encoded when the request is sent. A GET request becomes POST.

Form
RESTBuilder.url('https://example.com/login/').urlencoded({ name: 'peter', password: 'x' }).callback(console.log);
method

builder.xml([data])

Sends an XML body.
ParameterTypeDescription
data? String The XML.

Returns RESTBuilder The same builder, for chaining.

Sets Content-Type: text/xml and the body. Pass the XML as a string. A GET request becomes POST.

XML body
RESTBuilder.url('https://soap.example.com/').xml('<request><id>100</id></request>').callback(console.log);
method

builder.raw(value, [type])

Sets the body as it is.
ParameterTypeDescription
value String|Buffer The body.
type? String The short content type.

Returns RESTBuilder The same builder, for chaining.

Sets the body without any serialization. type is one of the short types of REQUEST() ('json', 'urlencoded', 'xml', 'html', 'plain', 'raw'); without it set the header with builder.type(). A string is sent unchanged. A Buffer needs the type 'raw' (application/octet-stream); without a type it is serialized as JSON like an object.

Binary body
RESTBuilder.url('https://api.example.com/images/').post().raw(buffer, 'raw').callback(console.log);
method

builder.text(value)

Sends plain text and keeps the response unparsed.
ParameterTypeDescription
value String The text.

Returns RESTBuilder The same builder, for chaining.

builder.plain(value) is an alias. Sets Content-Type: text/plain and the body, and the callback receives the raw response body instead of a parsed value.

Plain text
RESTBuilder.url('https://api.example.com/echo/').post().text('Hello').callback(function(err, response) {
	// response is the raw body
});
method

builder.file(name, filename, [source])

Adds a file and sends a multipart request.
ParameterTypeDescription
name String The form field name.
filename String The file name sent to the service.
source? Buffer|String A buffer, a path or a URL.

Returns RESTBuilder The same builder, for chaining.

The request becomes multipart/form-data (a GET becomes POST). source is a Buffer, a path on the disk, or a URL that is downloaded and streamed. Without source the file is read from filename. The body set with json() or urlencoded() is sent as extra form fields when it is an object.

Upload two files
RESTBuilder.POST('https://files.example.com/upload/')
	.file('photo', 'photo.jpg', PATH.tmp('photo.jpg'))
	.file('logo', 'logo.png', 'https://cdn.example.com/logo.png')
	.callback(console.log);
method

builder.header(name, value)

Sets a request header.
ParameterTypeDescription
name String The header name.
value String The value.

Returns RESTBuilder The same builder, for chaining.

Sets one header. Helpers for common headers: builder.referrer(url) (alias referer()) sets Referer, builder.origin(url) sets Origin, builder.csrf(token) sets X-Csrf-Token and builder.xhr() adds X-Requested-With: XMLHttpRequest.

Headers
builder.header('X-Token', CONF.apitoken).origin('https://www.example.com').xhr();
method

builder.type(value)

Sets the Content-Type header.
ParameterTypeDescription
value String The MIME type.

Returns RESTBuilder The same builder, for chaining.

Sets Content-Type to a full MIME type. A type set by json(), urlencoded(), xml() or text() replaces it, so use it with raw(value).

Custom type
builder.raw('{"id":1}').type('application/vnd.api+json');
method

builder.accept(ext)

Sets the Accept header.
ParameterTypeDescription
ext String An extension or a MIME type.

Returns RESTBuilder The same builder, for chaining.

Takes a file extension ('json', 'xml', 'html'...) and converts it to its MIME type; a longer value is used as it is.

Accept XML
builder.accept('xml');
method

builder.auth(user, [password])

Sets the Authorization header.
ParameterTypeDescription
user String The user name or the whole header value.
password? String The password.

Returns RESTBuilder The same builder, for chaining.

With user and password sets basic authentication (Basic base64(user:password)). With one argument the value is used as it is, for example 'Bearer TOKEN'.

Basic and Bearer
builder.auth('admin', 'secret');
builder.auth('Bearer ' + CONF.apitoken);
method

builder.cookie(name, value)

Adds a cookie to the request.
ParameterTypeDescription
name String The cookie name.
value String The value.

Returns RESTBuilder The same builder, for chaining.

Adds one cookie. builder.cookies(obj) replaces all cookies with an object { name: value }.

Cookies
builder.cookie('session', token);
builder.cookies({ lang: 'en', theme: 'dark' });
method

builder.cook([value])

Keeps the response cookies in the builder.
ParameterTypeDescription
value? Boolean false turns it off. Default: true

Returns RESTBuilder The same builder, for chaining.

With cook() the cookies set by the response are stored in the builder and sent with the next request made by the same builder. output.cookies then holds them. cook(false) turns it off.

Login, then read
RESTBuilder.url('https://example.com/login/').cook().urlencoded({ name: 'peter', password: 'x' }).callback(function(err, response, output) {
	RESTBuilder.GET('https://example.com/profile/').cookies(output.cookies).callback(console.log);
});
method

builder.timeout(ms)

Sets the timeout.
ParameterTypeDescription
ms Number Milliseconds.

Returns RESTBuilder The same builder, for chaining.

The timeout in milliseconds (10000 by default). 0 disables it. When it expires the error is 408: Request Timeout.

Five seconds
builder.timeout(5000);
method

builder.keepalive([val])

Reuses connections with a keep-alive agent.
ParameterTypeDescription
val? Boolean Turns keep-alive on or off. Default: true

Returns RESTBuilder The same builder, for chaining.

Without an argument (or with a truthy value) the request uses the shared keep-alive agent of the framework, so connections to the same host are reused. keepalive(false) turns it off. Not used together with a proxy.

Keep-alive
RESTBuilder.GET('https://api.example.com/ping/').keepalive().callback(console.log);
method

builder.proxy(url)

Sends the request through a proxy.
ParameterTypeDescription
url String The proxy.

Returns RESTBuilder The same builder, for chaining.

url is 'host:port' or 'http://host:port'. With http://user:password@host:port the credentials are sent as Proxy-Authorization: Basic. HTTPS targets are tunneled with CONNECT. Without it the proxy of the configuration key $proxyrequest is used when set.

Proxy
builder.proxy('http://10.0.0.5:3128');
Proxy with a login
builder.proxy('http://user:secret@10.0.0.5:3128');
method

builder.insecure()

Accepts invalid TLS certificates.

Returns RESTBuilder The same builder, for chaining.

Accepts self-signed or expired certificates of the service. Use it only for internal services.

Self-signed
RESTBuilder.GET('https://10.0.0.20/api/').insecure().callback(console.log);
method

builder.cert(key, cert, [dhparam])

Sets a client TLS certificate.
ParameterTypeDescription
key Buffer The private key.
cert Buffer The certificate.
dhparam? Buffer Diffie-Hellman parameters.

Returns RESTBuilder The same builder, for chaining.

For services that require client certificates.

Client certificate
builder.cert(Total.Fs.readFileSync(PATH.root('client.key')), Total.Fs.readFileSync(PATH.root('client.crt')));
method

builder.unixsocket(socket, path)

Sends the request through a Unix socket.
ParameterTypeDescription
socket String The socket file.
path String The request path, for example /api/.

Returns RESTBuilder The same builder, for chaining.

Connects to the socket file instead of a host; path is the URL path of the request.

Docker API
RESTBuilder.make(function(builder) {
	builder.unixsocket('/var/run/docker.sock', '/containers/json');
	builder.callback(console.log);
});
method

builder.nodnscache()

Turns off the DNS cache for this request.

Returns RESTBuilder The same builder, for chaining.

By default the builder resolves the hostname once and caches its addresses. With nodnscache() Node.js resolves it for every request.

No DNS cache
builder.nodnscache();
method

builder.redirect(value)

Turns following redirects on or off.
ParameterTypeDescription
value Boolean false stops following redirects.

Returns RESTBuilder The same builder, for chaining.

redirect(false) returns the 301 or 302 response itself; read the target in output.headers.location. By default up to four redirects are followed.

Read the location
RESTBuilder.GET('https://example.com/short/abc').redirect(false).callback(function(err, response, output) {
	console.log(output.status, output.headers.location);
});
method

builder.encrypt(key)

Encrypts the body and decrypts the response.
ParameterTypeDescription
key String The encryption key.

Returns RESTBuilder The same builder, for chaining.

The body is encrypted with key and sent with the header X-Encryption: a; a text response is decrypted with the same key. Both sides must use the same key.

Encrypted call
builder.encrypt(CONF.sharedkey);
method

builder.progress(fn)

Reports the download progress.
ParameterTypeDescription
fn Function function(percentage).

Returns RESTBuilder The same builder, for chaining.

Calls fn(percentage) for every received chunk. The percentage is known only when the response has Content-Length, otherwise it is 0.

Progress
builder.progress(function(percentage) {
	console.log(percentage.toFixed(1) + '%');
});
method

builder.noparse()

Returns the raw response body.

Returns RESTBuilder The same builder, for chaining.

The callback receives the body as a string (or a Buffer for binary types) instead of a parsed value.

Raw HTML
RESTBuilder.GET('https://example.com/').noparse().callback(function(err, html) {
	console.log(html.length);
});
method

builder.base64()

Returns the response body as base64.

Returns RESTBuilder The same builder, for chaining.

The callback receives the body encoded in base64, for example to embed an image as a data URI.

Data URI
RESTBuilder.GET('https://cdn.example.com/logo.png').base64().callback(function(err, data) {
	var uri = 'data:image/png;base64,' + data;
});
method

builder.debug()

Prints the request and the response to the console.

Returns RESTBuilder The same builder, for chaining.

After the response arrives prints the status, the method, the URL with the query, the error and the raw body.

Debug
RESTBuilder.GET('https://api.example.com/products/').debug().callback(NOOP);
method

builder.callback([fn])

Sends the request and receives the parsed response.
ParameterTypeDescription
fn? Function|Object function(err, response, output) or the $ of an action.

Returns RESTBuilder|Promise The builder, or a promise when called without an argument.

Sends the request on the next tick and passes the result to fn(err, response, output):

  • response: the body parsed by its Content-Type (JSON, also for text/plain; URL-encoded; XML through the HTML parser; other bodies are parsed as JSON when they look like JSON). An empty body gives an empty object; a 204 response gives true.
  • output: status, headers, response (the raw body), hostname, origin, cookies (with cook()) and output.cookie(name), which reads a cookie of the response.
  • err: the network error or '408: Request Timeout'; an ErrorBuilder when the body is a Total.js error array ([{ error: '...' }], response is then null); otherwise, for a status of 400 or more, an ErrorBuilder with one error whose name is the status code and whose message is the raw body. A value set with builder.error() replaces any error.

fn can also be the $ of an action: the parsed response is passed to $.callback() and an error is added to the errors of $. Without an argument it returns a promise that resolves with response and rejects with err.

Callback
RESTBuilder.GET('https://api.example.com/products/').callback(function(err, response, output) {
	if (err)
		return console.log(err);
	console.log(output.status, response.length);
});
In an action
NEWACTION('Products/sync', {
	name: 'Sync products',
	action: function($) {
		RESTBuilder.GET(CONF.shopapi + '/products/').callback($);
	}
});
method

builder.promise([$])

Sends the request and returns a promise.
ParameterTypeDescription
$? Object The $ of an action.

Returns Promise Resolves with the parsed response.

The promise resolves with the parsed response. On an error it rejects with an Error made from the error (an ErrorBuilder becomes an Error with its messages). With $ the error goes to $.invalid() instead and the promise is not rejected.

await
var user = await RESTBuilder.GET('https://api.example.com/users/100/').promise();
With $
var order = await RESTBuilder.POST(CONF.shopapi + '/orders/', model).promise($);
method

builder.exec([callback])

Sends the request at once.
ParameterTypeDescription
callback? Function function(err, response, output).

Returns RESTBuilder The same builder, for chaining.

Sends the request immediately and calls callback(err, response, output) with the same values as callback(). Prefer callback(), which waits for the next tick. When callback is omitted the result is ignored.

Exec
RESTBuilder.GET('https://api.example.com/ping/').exec(function(err, response) {
	console.log(err, response);
});
method

builder.stream(callback)

Returns the response as a stream.
ParameterTypeDescription
callback Function function(err, response).

Returns RESTBuilder The same builder, for chaining.

Sends the request on the next tick and calls callback(err, response) as soon as the headers arrive. response has status, headers, origin and stream (the Node.js response, not read yet). Use it for large files.

Save a large file
RESTBuilder.GET('https://cdn.example.com/backup.zip').stream(function(err, response) {
	if (!err && response.status === 200)
		response.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('backup.zip')));
});
method

builder.error(value)

since 0.0.16 Replaces any error with your own value.
ParameterTypeDescription
value Object|String The error to return, for example a message or an ErrorBuilder.

Returns RESTBuilder The same builder, for chaining.

When the request ends with any error (network, timeout or a status of 400 or more), the callback or the promise receives value instead. Use it to hide the details of a remote service from your users.

Own error
RESTBuilder.GET(CONF.stockapi).error('The stock service is not available').callback($);
method

builder.logerror()

since 0.0.16 Prints errors to the console.

Returns RESTBuilder The same builder, for chaining.

When the request ends with an error, the error (or the raw response body) is passed to the framework error handler, which prints it with the name RESTBuilder and the method and URL of the request. The callback still receives the error.

Log errors
RESTBuilder.POST(CONF.crmapi + '/contacts/', model).logerror().callback($);
Made in Europe