APIs
NEWAPI(), API() and its methods, TotalAPI() and their configuration keys.
On this page
The functions and configuration keys of named APIs, including the Total.js API service. The guide APIs explains how they work together with examples; this page is the exact reference.
API
method
NEWAPI(name, [config], callback)
Registers the code that calls one API service.
NEWAPI(name, [config], callback)| Parameter | Type | Description |
|---|---|---|
name |
String |
The name, or names separated by commas. |
config? |
Object |
Default settings copied into opt.config. |
callback |
Function |
function(opt, next); next(err, response) ends the call. |
Registers the handler of an API service. this in the handler is the API call. A name is found in the spelling given to NEWAPI() or in lower case; several names separated by commas share one handler. The name * handles every name without its own handler. A function alone, or a config object and a function, registers the name default. The optional config holds default settings: before each call its keys are copied into opt.config, unless the call already set them with .configure(). Pass null as the callback to remove a handler. F.newapi() is the same function.
NEWAPI('Weather', { region: 'eu' }, function(opt, next) {
REQUEST({ url: 'https://' + opt.config.region + '.weather.example/' + opt.schema + '/', method: 'POST', type: 'json', body: JSON.stringify(opt.data), callback: function(err, response) {
next(err, response && response.body.parseJSON());
}});
});
type
function(opt, next)
The options a NEWAPI() handler receives.
function(opt, next)The first argument of a NEWAPI() handler. It holds opt.name (the lower-case name of the service), opt.schema (the operation), opt.data, opt.controller (the $ of the call), opt.output (set by .output()), opt.files (an array of { name, filename, path } added by .file()), opt.retries (how many times the call was retried), opt.config (the config of NEWAPI() merged with .configure()) and opt.api (the API call). opt.retry() runs the handler again on the next tick and increases opt.retries.
NEWAPI('Weather', function(opt, next) {
callservice(opt.schema, opt.data, function(err, response) {
if (err && opt.retries < 3)
opt.retry();
else
next(err, response);
});
});
method
API(name, schema, data, [$])
Calls a service registered with NEWAPI().
API(name, schema, data, [$])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the service. |
schema |
String |
The operation, passed as opt.schema. |
data |
Object |
The payload, passed as opt.data. |
$? |
Object |
The $ of an action or a controller. |
Returns APICall The call with the methods below.
Creates the call and runs the handler on the next tick, so you configure the call with its methods right away. $ becomes opt.controller. When no handler matches (and no * handler exists), the call fails with API is not initialized. F.api() is the same function.
NEWACTION('weather_read', {
input: '*city:String',
action: function($, model) {
API('Weather', 'current', model).callback($);
}
});
method
API().callback(fn)
Sets the callback of the call.
API().callback(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function|Object |
A callback, or $. |
Returns APICall
fn is function(err, response), or the $ of an action, whose $.callback() receives the result. .pipe() is an alias.
API('Weather', 'current', { city: 'Oslo' }).callback(function(err, response) {
console.log(err, response);
});
method
API().promise([$])
Returns a promise of the call.
API().promise([$])| Parameter | Type | Description |
|---|---|---|
$? |
Object |
The $ of an action. |
Returns Promise
The promise resolves with the response. On an error it rejects with an Error; when $ is given, the error goes to $.invalid() instead.
var weather = await API('Weather', 'current', { city: 'Oslo' }).promise($);
method
API().data(fn)
Runs a function with the response of a successful call.
API().data(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function(response). |
Returns APICall
fn(response) runs before the callback.
API('Weather', 'current', { city: 'Oslo' }).data(function(response) {
MAIN.weather = response;
});
method
API().fail(fn)
Runs a function with the error of a failed call.
API().fail(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function |
function(err). |
Returns APICall
fn(err) runs before the callback.
API('Weather', 'current', { city: 'Oslo' }).fail(function(err) {
console.error(err);
});
method
API().error(message, [reverse])
Turns an empty response into an error.
API().error(message, [reverse])| Parameter | Type | Description |
|---|---|---|
message |
String |
The error. |
reverse? |
Boolean |
Fail on a non-empty response. Default: false |
Returns APICall
When the handler answers without an error but the response is empty (a falsy value or an empty array), the call fails with message. With reverse, it fails when the response is truthy (an empty array too). .err() is an alias.
API('Weather', 'current', model).error('City not found').callback($);
method
API().output(type)
Sets the output format of the call.
API().output(type)| Parameter | Type | Description |
|---|---|---|
type |
String |
The format, e.g. json, base64, stream. |
Returns APICall
The value is stored in opt.output for the handler. See TotalAPI() for the formats of the TAPI service.
API('Weather', 'map', { city: 'Oslo' }).output('base64').callback(console.log);
method
API().file(filename, path, [name])
Adds a file to the call.
API().file(filename, path, [name])| Parameter | Type | Description |
|---|---|---|
filename |
String |
The name of the file. |
path |
String |
The path of the file on the disk. |
name? |
String |
The field name. Default: file + index |
Returns APICall
The file is added to opt.files as { name, filename, path }. The default name is file0, file1, ...
API('Storage', 'upload', { folder: 'invoices' }).file('invoice.png', PATH.public('invoice.png')).callback(console.log);
method
API().controller($)
Sets the controller of the call.
API().controller($)| Parameter | Type | Description |
|---|---|---|
$ |
Object |
The $ of an action or a controller. |
Returns APICall
Stores $.controller (or $ itself when it has none) in opt.controller.
API('Weather', 'current', model).controller($).callback($);
method
API().audit($, message, [type])
Writes an audit log after a successful call.
API().audit($, message, [type])| Parameter | Type | Description |
|---|---|---|
$ |
Object |
The $ of an action. |
message |
String |
The message. |
type? |
String |
The type of the log. |
Returns APICall
Calls $.audit(message, type) once the call succeeds. Placeholders in the message such as {data.id} are filled from the data of the call, and {user.name} from the user of $.
API('Billing', 'invoice_create', model).audit($, 'Invoice for {data.email}').callback($);
method
API().debug()
Prints the result of the call to the console.
API().debug()Returns APICall
Prints the name, the operation, the error and the response.
API('Weather', 'current', { city: 'Oslo' }).debug().callback(NOOP);
method
API().configure(obj)
since 0.0.16
Sets configuration keys of the call.
API().configure(obj)| Parameter | Type | Description |
|---|---|---|
obj |
Object |
The keys to set. |
Returns APICall
Copies the keys of obj into opt.config. They override the config given to NEWAPI(). The TAPI service reads token from it.
API('TAPI', 'check', {}).configure({ token: CONF.customer_token }).callback(console.log);
method
TotalAPI(schema, data, [callback])
Calls an operation of Total.js API.
TotalAPI(schema, data, [callback])| Parameter | Type | Description |
|---|---|---|
schema |
String |
The operation, e.g. check. |
data |
Object |
The payload. |
callback? |
Function |
function(err, response). |
Returns APICall Configure it like any API() call.
The same as API('TAPI', schema, data). The TAPI (or TotalAPI) service sends a POST request to https://<$tapiurl>.api.totaljs.com/<schema>/ with the token from .configure({ token }), CONF.totalapi, CONF.secret_totalapi or CONF.$tapisecret and the app name. When $tapi is false, every operation except check fails with totalapi_inactive. A non-object data is sent as { value: data }. With .output() the response is json (default), html, plain, text, buffer, binary, base64, stream, or #storage [id] [filename], which saves it into that FileStorage. A response with a status above 200 fails with the error from Total API.
TotalAPI('check', {}, function(err, response) {
console.log(err, response);
});
// operation: a Total API operation that returns a file
API('TAPI', operation, data).output('#files').callback(console.log);
config
totalapi : token
The token of Total.js API.
totalapi : tokenReturns String
A string longer than five characters is stored as CONF.secret_totalapi and sent by the TAPI service. Any other value (true, false) is stored as $tapi.
// /config
totalapi : your-totalapi-token
config
$tapi : true
Allows calls of the TAPI service.
$tapi : trueReturns Boolean
Default true. When false, every TAPI operation except check fails with totalapi_inactive.
config
$tapiurl : eu
The region of Total.js API.
$tapiurl : euReturns String
Default eu. Requests go to https://<$tapiurl>.api.totaljs.com/.