Spanish Total.js
English
Documentation For AI agents
Contents

HTTP requests

RESTBuilder, REQUEST() and DOWNLOAD(): the clients for other HTTP services.

.md GitHub
On this page

The global functions and the RESTBuilder methods that send requests to other services. The guide HTTP requests explains how to use them with examples; this page is the exact reference.

API

method

REQUEST(options, [callback])

Sends an HTTP request and returns the raw response.
ParameterTypeDescription
options Object The options of the request (see the table).
callback? Function function(err, response). Without it the method returns a promise.

Returns Promise|undefined A promise of the response when you do not pass a callback.

The low-level HTTP client of the framework; RESTBuilder and DOWNLOAD() use it. Without a callback it returns a promise of the response.

Options

OptionTypeDescription
urlStringThe address (http:// or https://)
methodStringThe HTTP method, default GET
headersObjectRequest headers
queryObject/StringAppended to the URL as a query string
bodyString/BufferThe body; with files, an object of form fields
typeStringSets Content-Type: json, urlencoded, xml, plain, html or raw (application/octet-stream)
filesArrayFiles to upload as multipart/form-data: { name, filename, buffer }, { name, filename, path } or { name, filename, url }
cookiesObjectCookies to send, as { name: value }
cookBooleanCollects cookies of the responses (also from redirects) into options.cookies
timeoutNumberMilliseconds; default CONF.default_restbuilder_timeout (10000); 0 turns it off
encodingStringEncoding of a text response, default utf8; binary returns a Buffer
customBooleanReturns response.stream instead of reading the body
noredirectBooleanDoes not follow 301 and 302 redirects
keepaliveBooleanReuses connections (not with a proxy)
proxyStringA proxy server, for example http://user:pass@host:8080
resolve / dnscacheBooleanResolves the host name once and caches the address
xhrBooleanAdds X-Requested-With: XMLHttpRequest
unixsocketObject{ socket, path } sends the request to a Unix socket instead of url
key, cert, dhparamBufferTLS client certificate
insecureBooleanAccepts invalid TLS certificates
compressStringCompresses the body with gzip or deflate and sets Content-Encoding
encryptStringEncrypts the body with this key (header X-Encryption) and decrypts a text response
onprogressFunctionfn(percentage) while the body downloads
ondataFunctionfn(chunk, percentage) for every chunk
callbackFunctionThe same as the callback argument

Response: status, headers, body, host, origin (the resolved addresses, with resolve) and cookies; with custom: true, stream instead of body. Errors: Invalid hostname, the text of status 408 after a timeout, Too many redirects after four redirects, or a network error (then status is 0).

GET with a callback
REQUEST({ url: 'https://api.example.com/status/', timeout: 5000 }, function(err, response) {
	if (err) {
		console.log(err);
		return;
	}
	console.log(response.status, response.body);
});
POST JSON with a promise
var response = await REQUEST({
	url: 'https://api.example.com/items/',
	method: 'POST',
	type: 'json',
	body: JSON.stringify({ name: 'Item' })
});
var data = response.body.parseJSON();
Read a stream
REQUEST({ url: 'https://www.example.com/big.csv', custom: true }, function(err, response) {
	if (!err)
		response.stream.pipe(Fs.createWriteStream(PATH.temp('big.csv')));
});
method

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

Downloads a URL into a file.
ParameterTypeDescription
url String|Object An absolute or relative URL, or { socket, path }.
filename String The target file.
callback? Function function(err, response).
timeout? Number Milliseconds. Default: CONF.default_restbuilder_timeout

Returns Promise|undefined A promise of the response when you do not pass a callback.

Sends a GET request and writes the response body into filename. The callback runs when the file is written. Without a callback the method returns a promise.

A relative URL (for example /sitemap.xml) is requested from your own application; before the application is loaded the call waits. An object { socket, path } instead of the URL sends the request to a Unix socket.

The response has status, headers and filename. The status code is not checked: the file is written for 404 too.

Save an image
DOWNLOAD('https://www.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {
	if (err || response.status !== 200)
		console.log('Download failed');
});
With await
var response = await DOWNLOAD('https://www.example.com/data.json', PATH.databases('data.json'), null, 30000);
method

RESTBuilder.GET(url, [data])

Creates a builder for a GET request.
ParameterTypeDescription
url String The address.
data? Object Query string arguments.

Returns RESTBuilder A new builder.

data becomes the query string of the URL. Send the request with callback(), exec(), promise() or stream().

Load a list
RESTBuilder.GET('https://api.example.com/products/', { page: 2, limit: 50 }).callback(function(err, response) {
	// GET https://api.example.com/products/?page=2&limit=50
	console.log(response);
});
method

RESTBuilder.POST(url, [data])

Creates a builder for a POST request.
ParameterTypeDescription
url String The address.
data? Object The body, sent as JSON.

Returns RESTBuilder A new builder.

The data is sent as JSON. Call urlencoded() or xml() to send another format.

POST request
RESTBuilder.POST('https://api.example.com/products/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {
	console.log(output.status, response);
});
method

RESTBuilder.PUT(url, [data])

Creates a builder for a PUT request.
ParameterTypeDescription
url String The address.
data? Object The body, sent as JSON.

Returns RESTBuilder A new builder.

The data is sent as JSON.

PUT request
RESTBuilder.PUT('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {
	console.log(output.status, response);
});
method

RESTBuilder.PATCH(url, [data])

Creates a builder for a PATCH request.
ParameterTypeDescription
url String The address.
data? Object The body, sent as JSON.

Returns RESTBuilder A new builder.

The data is sent as JSON.

PATCH request
RESTBuilder.PATCH('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {
	console.log(output.status, response);
});
method

RESTBuilder.DELETE(url, [data])

Creates a builder for a DELETE request.
ParameterTypeDescription
url String The address.
data? Object The body, sent as JSON.

Returns RESTBuilder A new builder.

The data, if any, is sent as JSON.

DELETE request
RESTBuilder.DELETE('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {
	console.log(output.status, response);
});
method

RESTBuilder.HEAD(url)

Creates a builder for a HEAD request.
ParameterTypeDescription
url String The address.

Returns RESTBuilder A new builder.

Read the answer from output.status and output.headers in the callback.

Does the file exist?
RESTBuilder.HEAD('https://cdn.example.com/files/report.pdf').callback(function(err, response, output) {
	console.log(output.status === 200, output.headers['content-length']);
});
method

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

Calls an operation of a Total.js API endpoint.
ParameterTypeDescription
url String The address of the API endpoint.
name String The name of the operation, with its parameters (for example products_read/P01).
data? Object The data of the operation.

Returns RESTBuilder A new builder.

Sends a POST with the JSON body { schema: name, data: data }, the format that Total.js API routes read.

Call an operation
RESTBuilder.API('https://app.example.com/admin/', 'products_save', { name: 'Bike' }).callback(function(err, response) {
	console.log(err, response);
});
method

RESTBuilder.make(fn)

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

Returns RESTBuilder The new builder.

fn(builder) sets the URL, method and everything else. RESTBuilder.url(url) creates a builder with a URL only, and the instance method builder.make(fn) calls fn with the builder as this and as the argument.

Build the request
RESTBuilder.make(function(builder) {
	builder.url('https://api.example.com/orders/');
	builder.post({ product: 'P01' });
	builder.header('X-Token', CONF.token);
	builder.callback(console.log);
});
method

RESTBuilder.upgrade(fn)

Changes every builder before it sends its request.
ParameterTypeDescription
fn Function function(builder).

Returns undefined

fn(builder) runs in exec() for every builder of the application, after the body is prepared and before the request is sent. Register it once, in a definition file.

Add a header to all requests
// definitions/restbuilder.js
RESTBuilder.upgrade(function(builder) {
	builder.header('X-App', 'eshop');
});
method

RESTBuilder.addTransform(name, fn, [isDefault])

Registers a function that changes parsed responses.
ParameterTypeDescription
name String The name of the transformation.
fn Function function(value, output) returning the new value.
isDefault? Boolean Use it for all builders. Default: false

Returns undefined

fn(value, output) runs with this as the builder and returns the new value. A builder uses it after setTransform(name); with isDefault, every new builder uses it. RESTBuilder.setDefaultTransform(name) changes the default and RESTBuilder.setDefaultTransform() removes it. The transformation does not run when the response is a Total.js error array that becomes err.

Unwrap a data envelope
RESTBuilder.addTransform('envelope', function(value, output) {
	return value && value.data ? value.data : value;
});

RESTBuilder.GET('https://api.example.com/users/').setTransform('envelope').callback(function(err, users) {
	console.log(users);
});
method

builder.url([url])

Reads or sets the URL.
ParameterTypeDescription
url? String The address.

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

Without an argument it returns the current URL.

Set the URL
var builder = RESTBuilder.GET('https://api.example.com/');
builder.url('https://api.example.com/v2/products/');
method

builder.method(method, [data])

Sets the HTTP method.
ParameterTypeDescription
method String For example POST or put.
data? Object The body, sent as JSON.

Returns RESTBuilder The builder, for chaining.

Lower-case names are converted to upper case. data is sent as JSON.

Choose the method
RESTBuilder.make(function(builder) {
	builder.url('https://api.example.com/items/P01/');
	builder.method('PUT', { price: 20 });
	builder.callback(console.log);
});
method

builder.get([data])

Switches to GET and sets the query string.
ParameterTypeDescription
data? Object Query string arguments.

Returns RESTBuilder The builder, for chaining.

data replaces the query. Alias builder.GET().

Query
RESTBuilder.make(function(builder) {
	builder.url('https://api.example.com/search/');
	builder.get({ q: 'bike' });
	builder.callback(console.log);
});
method

builder.post([data])

Switches to POST and sets the body.
ParameterTypeDescription
data? Object|String The body.

Returns RESTBuilder The builder, for chaining.

The body keeps the type set earlier (urlencoded(), xml()), otherwise it is JSON. Alias builder.POST().

POST
RESTBuilder.make(function(builder) {
	builder.url('https://api.example.com/orders/');
	builder.post({ product: 'P01', count: 1 });
	builder.callback(console.log);
});
method

builder.put([data])

Switches to PUT and sets the body.
ParameterTypeDescription
data? Object|String The body.

Returns RESTBuilder The builder, for chaining.

builder.patch([data]) and builder.delete([data]) work the same with PATCH and DELETE; builder.head() switches to HEAD. Each has an upper-case alias (PUT(), PATCH(), DELETE(), HEAD()).

PUT and DELETE
RESTBuilder.make(function(builder) {
	builder.url('https://api.example.com/items/P01/');
	builder.put({ price: 20 });
	builder.callback(console.log);
});

RESTBuilder.make(function(builder) {
	builder.url('https://api.example.com/items/P02/');
	builder.delete();
	builder.callback(console.log);
});
method

builder.header(name, value)

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

Returns RESTBuilder The builder, for chaining.

For a CSRF token you can also use builder.csrf(value) (X-Csrf-Token), and builder.origin(value) for Origin.

Token header
RESTBuilder.GET('https://api.example.com/me/').header('X-Token', CONF.token).callback(console.log);
method

builder.type(value)

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

Returns RESTBuilder The builder, for chaining.

It overrides the type that json(), xml() and the other body methods set.

Custom type
RESTBuilder.POST('https://api.example.com/events/').raw(JSON.stringify(data), 'json').type('application/vnd.api+json').callback(console.log);
method

builder.accept(type)

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

Returns RESTBuilder The builder, for chaining.

A short value is an extension (json, xml) and is converted to its content type; a longer value is used as it is.

Ask for XML
RESTBuilder.GET('https://api.example.com/feed/').accept('xml').callback(console.log);
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 builder, for chaining.

With a password it creates Basic authentication. Without it, user is the whole value, for example Bearer TOKEN.

Basic and Bearer
RESTBuilder.GET('https://api.example.com/').auth('admin', 'secret').callback(console.log);
RESTBuilder.GET('https://api.example.com/').auth('Bearer ' + CONF.token).callback(console.log);
method

builder.cookie(name, value)

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

Returns RESTBuilder The builder, for chaining.

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

Send a session cookie
RESTBuilder.GET('https://www.example.com/account/').cookie('session', token).callback(console.log);
method

builder.cook([enable])

Collects the cookies of the responses.
ParameterTypeDescription
enable? Boolean false turns it off. Default: true

Returns RESTBuilder The builder, for chaining.

Cookies set by the server, also during redirects, are stored in the object of cookies() and returned by output.cookie(name). Pass the same object to the next builder to keep a session.

Keep a session
var jar = {};
RESTBuilder.POST('https://www.example.com/login/', { name: 'user', password: 'pass' }).cookies(jar).cook().callback(function(err, response, output) {
	RESTBuilder.GET('https://www.example.com/account/').cookies(jar).callback(console.log);
});
method

builder.json([data])

Sends the body as JSON.
ParameterTypeDescription
data? Object|String The body.

Returns RESTBuilder The builder, for chaining.

A GET becomes a POST.

JSON body
RESTBuilder.make(function(builder) {
	builder.url('https://api.example.com/items/');
	builder.json({ name: 'Item' });
	builder.callback(console.log);
});
method

builder.urlencoded([data])

Sends the body as application/x-www-form-urlencoded.
ParameterTypeDescription
data? Object|String The body.

Returns RESTBuilder The builder, for chaining.

A GET becomes a POST. An object is encoded as a form.

Form body
RESTBuilder.POST('https://www.example.com/contact/').urlencoded({ email: 'info@example.com', message: 'Hello' }).callback(console.log);
method

builder.xml([data], [replace])

Sends the body as XML.
ParameterTypeDescription
data? String The XML.
replace? Boolean Passed to parseXML() for the response. Default: false

Returns RESTBuilder The builder, for chaining.

Sets Content-Type: text/xml; a GET becomes a POST. Send the XML as a string. An XML response is parsed with String.parseXML(); replace is its argument.

SOAP-like call
RESTBuilder.make(function(builder) {
	builder.url('https://service.example.com/rates/');
	builder.xml('<request><currency>EUR</currency></request>');
	builder.callback(console.log);
});
method

builder.plain([value])

Sends a text body and returns the response as text.
ParameterTypeDescription
value? String The body.

Returns RESTBuilder The builder, for chaining.

Sets Content-Type: text/plain. The response is not parsed: response is the raw body.

Read text
RESTBuilder.GET('https://www.example.com/robots.txt').plain().callback(function(err, text) {
	console.log(text);
});
method

builder.raw(value, type)

Sets the body and its type.
ParameterTypeDescription
value Object|String|Buffer The body.
type String The type of the body.

Returns RESTBuilder The builder, for chaining.

type is json, urlencoded, xml, plain, html or raw (application/octet-stream). An object is serialized when the request is sent, except for type raw: send a string or a Buffer there.

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

builder.set(name, [value])

Sets one field of the body.
ParameterTypeDescription
name String|Object The field, or an object of fields.
value? Object The value.

Returns RESTBuilder The builder, for chaining.

name can be an object with several fields. builder.rem(name) removes a field. With file(), the fields are sent as form fields.

Fields
RESTBuilder.POST('https://api.example.com/items/').set('name', 'Bike').set({ price: 150, stock: 3 }).callback(console.log);
method

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

Adds a file to upload.
ParameterTypeDescription
name String The name of the form field.
filename String The file name.
source? Buffer|String The content, a path or a URL.

Returns RESTBuilder The builder, for chaining.

The request becomes multipart/form-data, and a GET becomes a POST. source is a Buffer, a path or a URL; a URL is downloaded and forwarded. Without source, filename is read as a path and only its name is sent. The content type comes from the extension of filename.

Upload two files
RESTBuilder.POST('https://api.example.com/upload/')
	.file('photo', 'photo.jpg', PATH.public('img/photo.jpg'))
	.file('data', 'data.json', Buffer.from(JSON.stringify(data)))
	.callback(console.log);
method

builder.timeout(ms)

Sets the timeout.
ParameterTypeDescription
ms Number Milliseconds. Default: 10000

Returns RESTBuilder The builder, for chaining.

The default of a builder is 10000. After the timeout err is the text of status 408.

Short timeout
RESTBuilder.GET('https://api.example.com/health/').timeout(2000).callback(console.log);
method

builder.keepalive()

Reuses connections.

Returns RESTBuilder The builder, for chaining.

The request uses a shared keep-alive agent. It has no effect with a proxy.

Many calls to one host
RESTBuilder.GET('https://api.example.com/items/').keepalive().callback(console.log);
method

builder.proxy(url)

Sends the request through a proxy server.
ParameterTypeDescription
url String For example http://user:password@proxy.example.com:8080.

Returns RESTBuilder The builder, for chaining.

The URL can contain credentials. For all requests set CONF.default_proxy.

Proxy
RESTBuilder.GET('https://api.example.com/').proxy('http://proxy.example.com:3128').callback(console.log);
method

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

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

Returns RESTBuilder The builder, for chaining.

Use it for services that require client certificates. builder.insecure() accepts invalid server certificates (for testing only).

Client certificate
RESTBuilder.GET('https://bank.example.com/api/')
	.cert(Fs.readFileSync(PATH.root('client.key')), Fs.readFileSync(PATH.root('client.crt')))
	.callback(console.log);
method

builder.nodnscache()

Turns off the DNS cache for this request.

Returns RESTBuilder The builder, for chaining.

A builder resolves the host name once and keeps the address; this resolves it as usual. Local addresses are never cached.

Fresh DNS
RESTBuilder.GET('https://api.example.com/').nodnscache().callback(console.log);
method

builder.redirect(enable)

Turns following of redirects on or off.
ParameterTypeDescription
enable Boolean Follow redirects.

Returns RESTBuilder The builder, for chaining.

redirect(false) returns the 301 or 302 response itself. Redirects are followed by default.

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

builder.unixsocket(socket, path)

Sends the request to a Unix socket.
ParameterTypeDescription
socket String The path of the socket file.
path String The path of the request.

Returns RESTBuilder The builder, for chaining.

A URL set earlier becomes the path.

Local service
RESTBuilder.make(function(builder) {
	builder.unixsocket('/var/run/app.sock', '/api/status/');
	builder.callback(console.log);
});
method

builder.xhr()

Adds X-Requested-With: XMLHttpRequest.

Returns RESTBuilder The builder, for chaining.

XHR
RESTBuilder.GET('https://www.example.com/api/').xhr().callback(console.log);
method

builder.referrer(value)

Sets the Referer header.
ParameterTypeDescription
value String The URL.

Returns RESTBuilder The builder, for chaining.

Alias builder.referer().

Referer
RESTBuilder.GET('https://www.example.com/page/').referrer('https://www.example.com/').callback(console.log);
method

builder.encrypt([key])

Encrypts the body and decrypts the response.
ParameterTypeDescription
key? String The key. Default: DEF.secret_encryption

Returns RESTBuilder The builder, for chaining.

Uses the framework encryption with key, or DEF.secret_encryption, and adds X-Encryption. Both sides must use the same key.

Encrypted call
RESTBuilder.POST('https://node2.example.com/sync/', data).encrypt(CONF.sync_key).callback(console.log);
method

builder.cache(expire)

Caches a successful response.
ParameterTypeDescription
expire String For example 5 minutes.

Returns RESTBuilder The builder, for chaining.

A response with status 200 is stored in F.cache for expire; the key is made from the URL and the body. builder.nocache() skips the cache for one call.

Cache rates
RESTBuilder.GET('https://api.example.com/rates/').cache('1 hour').callback(console.log);
method

builder.schema(name)

Validates the response with a schema.
ParameterTypeDescription
name String The name of the schema.

Returns RESTBuilder The builder, for chaining.

The callback gets the model created by the schema. Errors of the schema and a status code 400 or higher come back as err. The method throws when the schema does not exist.

Validate the response
NEWSCHEMA('Rate', function(schema) {
	schema.define('currency', 'String(3)', true);
	schema.define('value', Number, true);
});

RESTBuilder.GET('https://api.example.com/rate/EUR/').schema('Rate').callback(function(err, rate) {
	console.log(err, rate);
});
method

builder.map(map)

Keeps and converts selected fields of the response.
ParameterTypeDescription
map String For example id:number,name:string,dtcreated:date:created.

Returns RESTBuilder The builder, for chaining.

map lists field:type pairs separated by commas. A third part renames the field: source:type:target. It works for an object and for an array of objects.

Map a list
RESTBuilder.GET('https://api.example.com/users/').map('id:number,name:string').callback(function(err, users) {
	console.log(users);
});
method

builder.convert(schema)

Converts fields of the response.
ParameterTypeDescription
schema String For example price:number,date:date.

Returns RESTBuilder The builder, for chaining.

The response goes through CONVERT(value, schema). It does not run together with schema().

Convert types
RESTBuilder.GET('https://api.example.com/order/1/').convert('total:number,created:date').callback(console.log);
method

builder.strict()

Treats status codes 400 and higher as errors.

Returns RESTBuilder The builder, for chaining.

Then err is the status code. Without it you must check output.status yourself.

Fail on 404
RESTBuilder.GET('https://api.example.com/items/X/').strict().callback(function(err, response) {
	if (err === 404)
		console.log('Not found');
});
method

builder.noparse()

Returns the raw body without parsing.

Returns RESTBuilder The builder, for chaining.

response is the body as text (or a Buffer for binary types).

Raw JSON
RESTBuilder.GET('https://api.example.com/export/').noparse().callback(function(err, body) {
	Fs.writeFile(PATH.temp('export.json'), body, NOOP);
});
method

builder.setTransform(name)

Uses a registered transformation.
ParameterTypeDescription
name String The name of the transformation.

Returns RESTBuilder The builder, for chaining.

See RESTBuilder.addTransform().

Use a transformation
RESTBuilder.GET('https://api.example.com/users/').setTransform('envelope').callback(console.log);
method

builder.progress(fn)

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

Returns RESTBuilder The builder, for chaining.

fn(percentage) runs for every chunk. It needs the Content-Length header of the response; without it the percentage is 0.

Progress
RESTBuilder.GET('https://www.example.com/large.json').progress(function(percentage) {
	console.log(percentage.floor(1) + '%');
}).callback(console.log);
method

builder.debug()

Logs the request and the response.

Returns RESTBuilder The builder, for chaining.

Prints the status, method, URL, error and raw body to the console.

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

builder.callback([fn])

Sends the request.
ParameterTypeDescription
fn? Function|Object function(err, response, output), or $.

Returns RESTBuilder|Promise The builder, or a promise without a function.

With a function, fn(err, response, output) runs with the result. Without a function, or with $ of a schema operation, the method returns a promise: with $, an error goes to $.invalid().

Callback
RESTBuilder.GET('https://api.example.com/items/').callback(function(err, response, output) {
	console.log(err, response, output.status);
});
Promise
var items = await RESTBuilder.GET('https://api.example.com/items/').callback();
method

builder.exec([callback])

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

Returns RESTBuilder The builder, for chaining.

callback(err, response, output) is the same as in callback(); exec() sends immediately, callback() on the next tick.

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

builder.promise([$])

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

Returns Promise A promise of the parsed response.

The promise resolves with the parsed response. With $ (the options of a schema operation), an error is passed to $.invalid() and the promise does not settle; without it the promise rejects.

In an operation
schema.action('sync', {
	name: 'Sync',
	action: async function($) {
		var items = await RESTBuilder.GET('https://api.example.com/items/').promise($);
		$.callback(items);
	}
});
method

builder.stream(callback)

Sends the request and returns the response as a stream.
ParameterTypeDescription
callback Function function(err, response).

Returns RESTBuilder The builder, for chaining.

callback(err, response) receives status, headers, origin and stream (the incoming message). The body is not read or parsed.

Pipe to a file
RESTBuilder.GET('https://www.example.com/export.csv').stream(function(err, response) {
	if (!err)
		response.stream.pipe(Fs.createWriteStream(PATH.temp('export.csv')));
});
method

output.cookie(name)

Reads a cookie from the response.
ParameterTypeDescription
name String The name of the cookie.

Returns String The value.

output is the third argument of the callback. The method reads the Set-Cookie headers, or the cookies collected by cook(), and returns the decoded value or an empty string.

Read a cookie
RESTBuilder.POST('https://www.example.com/login/', { name: 'user', password: 'pass' }).callback(function(err, response, output) {
	var session = output.cookie('session');
});
Made in Europe