HTTP requests
RESTBuilder, REQUEST() and DOWNLOAD(): the clients for other HTTP services.
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.
REQUEST(options, [callback])| Parameter | Type | Description |
|---|---|---|
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
| Option | Type | Description |
|---|---|---|
url | String | The address (http:// or https://) |
method | String | The HTTP method, default GET |
headers | Object | Request headers |
query | Object/String | Appended to the URL as a query string |
body | String/Buffer | The body; with files, an object of form fields |
type | String | Sets Content-Type: json, urlencoded, xml, plain, html or raw (application/octet-stream) |
files | Array | Files to upload as multipart/form-data: { name, filename, buffer }, { name, filename, path } or { name, filename, url } |
cookies | Object | Cookies to send, as { name: value } |
cook | Boolean | Collects cookies of the responses (also from redirects) into options.cookies |
timeout | Number | Milliseconds; default CONF.default_restbuilder_timeout (10000); 0 turns it off |
encoding | String | Encoding of a text response, default utf8; binary returns a Buffer |
custom | Boolean | Returns response.stream instead of reading the body |
noredirect | Boolean | Does not follow 301 and 302 redirects |
keepalive | Boolean | Reuses connections (not with a proxy) |
proxy | String | A proxy server, for example http://user:pass@host:8080 |
resolve / dnscache | Boolean | Resolves the host name once and caches the address |
xhr | Boolean | Adds X-Requested-With: XMLHttpRequest |
unixsocket | Object | { socket, path } sends the request to a Unix socket instead of url |
key, cert, dhparam | Buffer | TLS client certificate |
insecure | Boolean | Accepts invalid TLS certificates |
compress | String | Compresses the body with gzip or deflate and sets Content-Encoding |
encrypt | String | Encrypts the body with this key (header X-Encryption) and decrypts a text response |
onprogress | Function | fn(percentage) while the body downloads |
ondata | Function | fn(chunk, percentage) for every chunk |
callback | Function | The 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).
REQUEST({ url: 'https://api.example.com/status/', timeout: 5000 }, function(err, response) {
if (err) {
console.log(err);
return;
}
console.log(response.status, response.body);
});
var response = await REQUEST({
url: 'https://api.example.com/items/',
method: 'POST',
type: 'json',
body: JSON.stringify({ name: 'Item' })
});
var data = response.body.parseJSON();
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.
DOWNLOAD(url, filename, [callback], [timeout])| Parameter | Type | Description |
|---|---|---|
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.
DOWNLOAD('https://www.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {
if (err || response.status !== 200)
console.log('Download failed');
});
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.
RESTBuilder.GET(url, [data])| Parameter | Type | Description |
|---|---|---|
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().
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.
RESTBuilder.POST(url, [data])| Parameter | Type | Description |
|---|---|---|
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.
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.
RESTBuilder.PUT(url, [data])| Parameter | Type | Description |
|---|---|---|
url |
String |
The address. |
data? |
Object |
The body, sent as JSON. |
Returns RESTBuilder A new builder.
The data is sent as JSON.
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.
RESTBuilder.PATCH(url, [data])| Parameter | Type | Description |
|---|---|---|
url |
String |
The address. |
data? |
Object |
The body, sent as JSON. |
Returns RESTBuilder A new builder.
The data is sent as JSON.
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.
RESTBuilder.DELETE(url, [data])| Parameter | Type | Description |
|---|---|---|
url |
String |
The address. |
data? |
Object |
The body, sent as JSON. |
Returns RESTBuilder A new builder.
The data, if any, is sent as JSON.
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.
RESTBuilder.HEAD(url)| Parameter | Type | Description |
|---|---|---|
url |
String |
The address. |
Returns RESTBuilder A new builder.
Read the answer from output.status and output.headers in the callback.
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.
RESTBuilder.API(url, name, [data])| Parameter | Type | Description |
|---|---|---|
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.
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.
RESTBuilder.make(fn)| Parameter | Type | Description |
|---|---|---|
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.
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.
RESTBuilder.upgrade(fn)| Parameter | Type | Description |
|---|---|---|
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.
// 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.
RESTBuilder.addTransform(name, fn, [isDefault])| Parameter | Type | Description |
|---|---|---|
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.
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.
builder.url([url])| Parameter | Type | Description |
|---|---|---|
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.
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.
builder.method(method, [data])| Parameter | Type | Description |
|---|---|---|
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.
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.
builder.get([data])| Parameter | Type | Description |
|---|---|---|
data? |
Object |
Query string arguments. |
Returns RESTBuilder The builder, for chaining.
data replaces the query. Alias builder.GET().
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.
builder.post([data])| Parameter | Type | Description |
|---|---|---|
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().
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.
builder.put([data])| Parameter | Type | Description |
|---|---|---|
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()).
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.
builder.header(name, value)| Parameter | Type | Description |
|---|---|---|
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.
RESTBuilder.GET('https://api.example.com/me/').header('X-Token', CONF.token).callback(console.log);
method
builder.type(value)
Sets the Content-Type header.
builder.type(value)| Parameter | Type | Description |
|---|---|---|
value |
String |
The content type. |
Returns RESTBuilder The builder, for chaining.
It overrides the type that json(), xml() and the other body methods set.
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.
builder.accept(type)| Parameter | Type | Description |
|---|---|---|
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.
RESTBuilder.GET('https://api.example.com/feed/').accept('xml').callback(console.log);
method
builder.auth(user, [password])
Sets the Authorization header.
builder.auth(user, [password])| Parameter | Type | Description |
|---|---|---|
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.
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.
builder.cookie(name, value)| Parameter | Type | Description |
|---|---|---|
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 }.
RESTBuilder.GET('https://www.example.com/account/').cookie('session', token).callback(console.log);
method
builder.cook([enable])
Collects the cookies of the responses.
builder.cook([enable])| Parameter | Type | Description |
|---|---|---|
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.
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.
builder.json([data])| Parameter | Type | Description |
|---|---|---|
data? |
Object|String |
The body. |
Returns RESTBuilder The builder, for chaining.
A GET becomes a POST.
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.
builder.urlencoded([data])| Parameter | Type | Description |
|---|---|---|
data? |
Object|String |
The body. |
Returns RESTBuilder The builder, for chaining.
A GET becomes a POST. An object is encoded as a form.
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.
builder.xml([data], [replace])| Parameter | Type | Description |
|---|---|---|
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.
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.
builder.plain([value])| Parameter | Type | Description |
|---|---|---|
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.
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.
builder.raw(value, type)| Parameter | Type | Description |
|---|---|---|
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.
RESTBuilder.POST('https://api.example.com/blob/').raw(buffer, 'raw').callback(console.log);
method
builder.set(name, [value])
Sets one field of the body.
builder.set(name, [value])| Parameter | Type | Description |
|---|---|---|
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.
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.
builder.file(name, filename, [source])| Parameter | Type | Description |
|---|---|---|
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.
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.
builder.timeout(ms)| Parameter | Type | Description |
|---|---|---|
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.
RESTBuilder.GET('https://api.example.com/health/').timeout(2000).callback(console.log);
method
builder.keepalive()
Reuses connections.
builder.keepalive()Returns RESTBuilder The builder, for chaining.
The request uses a shared keep-alive agent. It has no effect with a proxy.
RESTBuilder.GET('https://api.example.com/items/').keepalive().callback(console.log);
method
builder.proxy(url)
Sends the request through a proxy server.
builder.proxy(url)| Parameter | Type | Description |
|---|---|---|
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.
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.
builder.cert(key, cert, [dhparam])| Parameter | Type | Description |
|---|---|---|
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).
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.
builder.nodnscache()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.
RESTBuilder.GET('https://api.example.com/').nodnscache().callback(console.log);
method
builder.redirect(enable)
Turns following of redirects on or off.
builder.redirect(enable)| Parameter | Type | Description |
|---|---|---|
enable |
Boolean |
Follow redirects. |
Returns RESTBuilder The builder, for chaining.
redirect(false) returns the 301 or 302 response itself. Redirects are followed by default.
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.
builder.unixsocket(socket, path)| Parameter | Type | Description |
|---|---|---|
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.
RESTBuilder.make(function(builder) {
builder.unixsocket('/var/run/app.sock', '/api/status/');
builder.callback(console.log);
});
method
builder.xhr()
Adds X-Requested-With: XMLHttpRequest.
builder.xhr()Returns RESTBuilder The builder, for chaining.
RESTBuilder.GET('https://www.example.com/api/').xhr().callback(console.log);
method
builder.referrer(value)
Sets the Referer header.
builder.referrer(value)| Parameter | Type | Description |
|---|---|---|
value |
String |
The URL. |
Returns RESTBuilder The builder, for chaining.
Alias builder.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.
builder.encrypt([key])| Parameter | Type | Description |
|---|---|---|
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.
RESTBuilder.POST('https://node2.example.com/sync/', data).encrypt(CONF.sync_key).callback(console.log);
method
builder.cache(expire)
Caches a successful response.
builder.cache(expire)| Parameter | Type | Description |
|---|---|---|
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.
RESTBuilder.GET('https://api.example.com/rates/').cache('1 hour').callback(console.log);
method
builder.schema(name)
Validates the response with a schema.
builder.schema(name)| Parameter | Type | Description |
|---|---|---|
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.
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.
builder.map(map)| Parameter | Type | Description |
|---|---|---|
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.
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.
builder.convert(schema)| Parameter | Type | Description |
|---|---|---|
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().
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.
builder.strict()Returns RESTBuilder The builder, for chaining.
Then err is the status code. Without it you must check output.status yourself.
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.
builder.noparse()Returns RESTBuilder The builder, for chaining.
response is the body as text (or a Buffer for binary types).
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.
builder.setTransform(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the transformation. |
Returns RESTBuilder The builder, for chaining.
See RESTBuilder.addTransform().
RESTBuilder.GET('https://api.example.com/users/').setTransform('envelope').callback(console.log);
method
builder.progress(fn)
Reports the progress of the download.
builder.progress(fn)| Parameter | Type | Description |
|---|---|---|
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.
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.
builder.debug()Returns RESTBuilder The builder, for chaining.
Prints the status, method, URL, error and raw body to the console.
RESTBuilder.GET('https://api.example.com/').debug().callback(console.log);
method
builder.callback([fn])
Sends the request.
builder.callback([fn])| Parameter | Type | Description |
|---|---|---|
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().
RESTBuilder.GET('https://api.example.com/items/').callback(function(err, response, output) {
console.log(err, response, output.status);
});
var items = await RESTBuilder.GET('https://api.example.com/items/').callback();
method
builder.exec([callback])
Sends the request at once.
builder.exec([callback])| Parameter | Type | Description |
|---|---|---|
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.
RESTBuilder.GET('https://api.example.com/ping/').exec(function(err, response) {
console.log(response);
});
method
builder.promise([$])
Sends the request and returns a promise.
builder.promise([$])| Parameter | Type | Description |
|---|---|---|
$? |
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.
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.
builder.stream(callback)| Parameter | Type | Description |
|---|---|---|
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.
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.
output.cookie(name)| Parameter | Type | Description |
|---|---|---|
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.
RESTBuilder.POST('https://www.example.com/login/', { name: 'user', password: 'pass' }).callback(function(err, response, output) {
var session = output.cookie('session');
});