Skip to contentSkip to navigationSkip to topbar
On this page

Runtime Client


The Twilio Runtime Client provides a direct way of orchestrating the various parts of the Twilio Runtime without requiring an imported module. Using the Runtime Client, developers can reference other Functions to better organize their code, access configuration and files stored in Assets, and manage real-time data via Twilio Sync.

Access the Runtime Client in a Function by referencing Runtime, which exposes the following API:


Methods

methods page anchor

getAssets()

getassets page anchor

The getAssets method returns an object that contains the names each private Asset in a Service. Each Asset name serves as the key to an Asset object that contains the path to that Asset, as well as an open method that can be conveniently used to access its contents. These paths can be used to retrieve files served on Twilio Assets.

For example, executing Runtime.getAssets() could return an object with the following private Assets:

1
{
2
'/names.json': {
3
path: '/var/task/files/ZNdad14da2e70d2533f640cf362fec0609',
4
open: [Function: open]
5
},
6
'/rickroll.mp3': {
7
path: '/var/task/files/ZNdfbfaf15a02e244fa11337548dabd9d0',
8
open: [Function: open]
9
},
10
'/helper-method.js': {
11
path: '/var/task/files/ZN5d6d933785a76da25056328a5764d49b',
12
open: [Function: open]
13
}
14
}
(warning)

Warning

getAssets() only returns private Assets. Public and protected assets can be accessed via their publicly facing urls without the need for calling getAssets(). Refer to the visibility guide for more context!

(warning)

Warning

Note that an Asset such as names.json will be returned with a key of '/names.json'. To correctly retrieve the Asset and its path, the leading / and extension must be part of the key used to access the object returned by Runtime.getAssets().

For example: Runtime.getAssets()['/names.json'].path

Asset Properties

asset-properties page anchor
PropertyTypeDescription
pathstringString specifying the location of the private Asset
openfunctionConvenience method that returns the contents of the file from path in utf8 encoding
(information)

Info

If you would like to include a JavaScript module that isn't available on npm, the best way to do so is to upload the module as a private Asset, then use getAssets in order to require the module as shown in the Load a module from an asset code example.

Retrieve the path of an Asset

retrieve-the-path-of-an-asset page anchor

Example of how to get the file path for an Asset

1
exports.handler = function (context, event, callback) {
2
// Note: the leading slash and file extension are necessary to access the Asset
3
const path = Runtime.getAssets()['/my-asset.json'].path;
4
5
console.log('The path is: ' + path);
6
7
return callback();
8
};

Load a module from an Asset

load-a-module-from-an-asset page anchor

Example of how to load a third party library stored in an Asset

1
exports.handler = function (context, event, callback) {
2
// First, get the path for the Asset
3
const path = Runtime.getAssets()['/answer-generator.js'].path;
4
5
// Next, you can use require() to import the library
6
const module = require(path);
7
8
// Finally, use the module as you would any other!
9
console.log('The answer to your riddle is: ' + module.getAnswer());
10
11
return callback();
12
};

Read the contents of an Asset

read-the-contents-of-an-asset page anchor

Leverage the built-in open method for convenience

1
exports.handler = function (context, event, callback) {
2
const openFile = Runtime.getAssets()['/my_file.txt'].open;
3
// Calling open is equivalent to using fs.readFileSync(asset.filePath, 'utf8')
4
const text = openFile();
5
6
console.log('Your file contents: ' + text);
7
8
return callback();
9
};

Read the contents of an Asset

read-the-contents-of-an-asset-1 page anchor

Directly read the contents of an Asset using filesystem methods

1
// We're reading a file from the file system, so we'll need to import fs
2
const fs = require('fs');
3
4
exports.handler = async function (context, event, callback) {
5
// Retrieve the path of your file
6
const file = Runtime.getAssets()['/my_file.txt'].path;
7
// Asynchronously read the file using a different encoding from utf8
8
const text = await fs.readFile(file, 'base64');
9
10
console.log('Your file contents: ' + text);
11
12
return callback();
13
};

The getFunctions method returns an object that contains the names of every Function in the Service. Each Function name serves as the key to a Function object that contains the path to that Function. These paths can be used to import code from other Functions and to compose code hosted on Twilio Functions.

For example, executing Runtime.getFunctions() could return an object with the following Functions:

1
{
2
'sms/reply': {
3
path: '/var/task/handlers/ZNdad14da2e70d2533f640cf362fec0609.js',
4
},
5
'helper': {
6
path: '/var/task/handlers/ZNdfbfaf15a02e244fa11337548dabd9d0.js',
7
},
8
'example-function': {
9
path: '/var/task/handlers/ZN5d6d933785a76da25056328a5764d49b.js',
10
},
11
}
(warning)

Warning

Note that, unlike an Asset, a Function such as sms/reply.js will be returned with a key of "sms/reply". To correctly retrieve the Function and its path, do not include characters such as a leading slash or the .js extension in the key used to access the object returned by Runtime.getFunctions().

For example: Runtime.getFunctions()["sms/reply"].path

PropertyTypeDescription
pathstringString specifying the location of the Function

Retrieve the path for a Function

retrieve-the-path-for-a-function page anchor

Example of how to retrieve the file path for a Function

1
exports.handler = function (context, event, callback) {
2
// Get the path for the Function. Note that the key of the function
3
// is not preceded by a "/" as is the case with Assets
4
const path = Runtime.getFunctions()['example-function'].path;
5
6
console.log('The path to your Function is: ' + path);
7
8
return callback();
9
};

Include a private Function in another Function

include-a-private-function-in-another-function page anchor

Private Functions are a great way to store methods that may be reused between your other Functions. For example, lets say we have a private Function called Zoltar that exports a fortune-generating method, ask:

Define a private helper Function

define-a-private-helper-function page anchor

Implement Zoltar and define an ask method

1
exports.ask = () => {
2
// We're not totally sure if Zoltar's advice is all that helpful
3
const fortunes = [
4
'A long-forgotten loved one will appear soon.',
5
'Are you sure the back door is locked?',
6
"Communicate! It can't make things any worse.",
7
'Do not sleep in a eucalyptus tree tonight.',
8
'Fine day for friends.',
9
'Good news. Ten weeks from Friday will be a pretty good day.',
10
'Living your life is a task so difficult, it has never been attempted before.',
11
'Stay away from flying saucers today.',
12
'The time is right to make new friends.',
13
'Try to relax and enjoy the crisis.',
14
'You need more time; and you probably always will.',
15
'Your business will assume vast proportions.',
16
];
17
18
// Generate a random index and return the given fortune
19
return fortunes[Math.floor(Math.random() * fortunes.length)];
20
};

You could then access this private method by using Runtime.getFunctions() to get the path for the Zoltar Function, import Zoltar as a JavaScript module using require, and then access the ask method as in the following code sample:

Include code from a Function

include-code-from-a-function page anchor

Example of how to include code from other Functions

1
exports.handler = function (context, event, callback) {
2
// First, get the path for the Function. Note that the key of the function
3
// is not preceded by a "/" as is the case with Assets
4
const zoltarPath = Runtime.getFunctions()['zoltar'].path;
5
6
// Next, use require() to import the library
7
const zoltar = require(zoltarPath);
8
9
// Finally, use the module as you would any other!
10
console.log('The answer to your riddle is: ' + zoltar.ask());
11
12
return callback();
13
}

We've made it convenient for you to access the Sync REST API from Functions. Use the Runtime Client to access any of Sync's real-time data primitives and store information between Function invocations. The same data can be accessed using the Sync API library, making Sync from Functions the perfect way to update your real-time apps and dashboards.

The Runtime Client provides a wrapper around the Twilio REST API Helper for Twilio Sync. By default, calling Runtime.getSync() will return a Sync Service object that has been configured to work with your default Sync Instance.

For added convenience and less typing, the following methods returned from getSync are renamed from their usual name in the Node.js SDK, as you will see in the examples.

Default method nameMethod name in Functions
syncMapsmaps
syncListslists

getSync optionally accepts a configuration object with the following properties.

ParameterTypeDescription
serviceNamestringString specifying either the serviceSid or uniqueName of the Sync Service to connect to. Defaults to default.

Get the default Sync Service Instance

get-the-default-sync-service-instance page anchor

Example of how to get the default Sync Service Instance

1
exports.handler = (context, event, callback) => {
2
// Use the getSync method with no arguments to get a reference to the default
3
// Sync document for your account. Fetch returns a Promise, which will
4
// eventually resolve to metadata about the Sync Service, such as its SID
5
Runtime.getSync()
6
.fetch()
7
.then((defaultSyncService) => {
8
console.log('Sync Service SID: ', defaultSyncService.sid);
9
return callback(null, defaultSyncService.sid);
10
})
11
.catch((error) => {
12
console.log('Sync Error: ', error);
13
return callback(error);
14
});
15
};

Get an existing Sync Service Instance

get-an-existing-sync-service-instance page anchor

Example of how to use Runtime Client to get an Sync Service Instance by providing the SID

1
exports.handler = (context, event, callback) => {
2
// Pass a serviceName to getSync to get a reference to that specific
3
// Sync document on your account. Fetch returns a Promise, which will
4
// eventually resolve to metadata about the Sync Service, such as friendlyName
5
Runtime.getSync({ serviceName: 'ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' })
6
.fetch()
7
.then((syncService) => {
8
console.log('Sync Service Name: ' + syncService.friendlyName);
9
return callback(null, syncService.friendlyName);
10
})
11
.catch((error) => {
12
console.log('Sync Error: ', error);
13
return callback(error);
14
});
15
};

Create a Sync Map using Runtime Client

create-a-sync-map-using-runtime-client page anchor

Example of how to create a Map in Sync with the Runtime Client

1
exports.handler = (context, event, callback) => {
2
// maps, which is a shortcut to syncMaps, allows you to create a new Sync Map
3
// instance. Be sure to provide a uniqueName identifier!
4
Runtime.getSync()
5
.maps.create({
6
uniqueName: 'spaceShips',
7
})
8
.then((newMap) => {
9
console.log(newMap);
10
return callback(null, newMap);
11
})
12
.catch((error) => {
13
console.log('Sync Error: ', error);
14
return callback(error);
15
});
16
};

Add entry to a Sync Map with Runtime Client

add-entry-to-a-sync-map-with-runtime-client page anchor

Example of how to add an entry to a Sync Map with the Runtime Client

1
exports.handler = (context, event, callback) => {
2
// Given an existing Sync Map with the uniqueName of spaceShips, you can use
3
// syncMapItems.create to add a new key:data pair which will be accessible
4
// to any other Function or product with access to the Sync Map!
5
Runtime.getSync()
6
.maps('spaceShips')
7
.syncMapItems.create({
8
key: 'fastestShip',
9
data: {
10
name: 'Millenium Falcon',
11
},
12
})
13
.then((response) => {
14
console.log(response);
15
return callback(null, response);
16
})
17
.catch((error) => {
18
console.log('Sync Error: ', error);
19
return callback(error);
20
});
21
};

Create a Sync List with Runtime Client

create-a-sync-list-with-runtime-client page anchor

Example of how to create Sync List with Runtime Client

1
exports.handler = (context, event, callback) => {
2
// If your use case warrants a list data structure instead of a map, you
3
// can instantiate a Sync List. As with Maps, be sure to provide a uniqueName!
4
Runtime.getSync()
5
.lists.create({
6
uniqueName: 'spaceShips',
7
})
8
.then((newList) => {
9
console.log(newList);
10
return callback(null, newList);
11
})
12
.catch((error) => {
13
console.log('Sync Error: ', error);
14
return callback(error);
15
});
16
};

Append to Sync List with Runtime Client

append-to-sync-list-with-runtime-client page anchor

Example of how to append to a Sync List using the Runtime Client

1
exports.handler = (context, event, callback) => {
2
// Given an existing Sync List with the uniqueName of spaceShips, you can use
3
// syncListItems.create to append a new data entry which will be accessible
4
// to any other Function or product with access to the Sync List!
5
Runtime.getSync()
6
.lists('spaceShips')
7
.syncListItems.create({
8
data: {
9
text: 'Millennium Falcon',
10
},
11
})
12
.then((response) => {
13
console.log(response);
14
return callback(null, response);
15
})
16
.catch((error) => {
17
console.log('Sync Error: ', error);
18
return callback(error);
19
});
20
};

Create a Sync Document with Runtime Client

create-a-sync-document-with-runtime-client page anchor

Example of how to create a Sync Document using the Runtime Client

1
exports.handler = (context, event, callback) => {
2
// Last but not least, it's also possible to create Sync Documents.
3
// As always, remember to provide a uniqueName to identify your Document.
4
Runtime.getSync()
5
.documents.create({
6
uniqueName: 'userPreferences',
7
data: {
8
greeting: 'Ahoyhoy!',
9
},
10
})
11
.then((newDoc) => {
12
console.log(newDoc);
13
return callback(null, newDoc);
14
})
15
.catch((error) => {
16
console.log('Sync Error: ', error);
17
return callback(error);
18
});
19
};

Perform multiple Sync actions in a Function

perform-multiple-sync-actions-in-a-function page anchor

Example of creating a Sync Map and adding data to it in the same Function execution

1
exports.handler = async (context, event, callback) => {
2
// Grab a reference to the Sync object since we'll be using it a few times
3
const sync = Runtime.getSync();
4
5
try {
6
// First, lets create a brand new Sync Map
7
const newMap = await sync.maps.create({ uniqueName: 'quicklyUpdatedMap' });
8
console.log('newMap: ', newMap);
9
10
// Now, let's access that map and add a new item to it.
11
// Be sure to specify a unique key and data for the item!
12
// Creation is an async operation, so we need to await it.
13
const newMapItem = await sync.maps(newMap.sid).syncMapItems.create({
14
key: 'fastestShip',
15
data: {
16
name: 'Millenium Falcon',
17
},
18
});
19
20
// Now that we have a new item, let's log and return it.
21
console.log('newMapItem: ', newMapItem);
22
return callback(null, newMapItem);
23
} catch (error) {
24
// Be sure to log and return any errors that occur!
25
console.error('Sync Error: ', error);
26
return callback(error);
27
}
28
};

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.