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:
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': {3path: '/var/task/files/ZNdad14da2e70d2533f640cf362fec0609',4open: [Function: open]5},6'/rickroll.mp3': {7path: '/var/task/files/ZNdfbfaf15a02e244fa11337548dabd9d0',8open: [Function: open]9},10'/helper-method.js': {11path: '/var/task/files/ZN5d6d933785a76da25056328a5764d49b',12open: [Function: open]13}14}
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!
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
Property | Type | Description |
---|---|---|
path | string | String specifying the location of the private Asset |
open | function | Convenience method that returns the contents of the file from path in utf8 encoding |
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.
Example of how to get the file path for an Asset
1exports.handler = function (context, event, callback) {2// Note: the leading slash and file extension are necessary to access the Asset3const path = Runtime.getAssets()['/my-asset.json'].path;45console.log('The path is: ' + path);67return callback();8};
Example of how to load a third party library stored in an Asset
1exports.handler = function (context, event, callback) {2// First, get the path for the Asset3const path = Runtime.getAssets()['/answer-generator.js'].path;45// Next, you can use require() to import the library6const module = require(path);78// Finally, use the module as you would any other!9console.log('The answer to your riddle is: ' + module.getAnswer());1011return callback();12};
Leverage the built-in open method for convenience
1exports.handler = function (context, event, callback) {2const openFile = Runtime.getAssets()['/my_file.txt'].open;3// Calling open is equivalent to using fs.readFileSync(asset.filePath, 'utf8')4const text = openFile();56console.log('Your file contents: ' + text);78return callback();9};
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 fs2const fs = require('fs');34exports.handler = async function (context, event, callback) {5// Retrieve the path of your file6const file = Runtime.getAssets()['/my_file.txt'].path;7// Asynchronously read the file using a different encoding from utf88const text = await fs.readFile(file, 'base64');910console.log('Your file contents: ' + text);1112return 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': {3path: '/var/task/handlers/ZNdad14da2e70d2533f640cf362fec0609.js',4},5'helper': {6path: '/var/task/handlers/ZNdfbfaf15a02e244fa11337548dabd9d0.js',7},8'example-function': {9path: '/var/task/handlers/ZN5d6d933785a76da25056328a5764d49b.js',10},11}
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
Property | Type | Description |
---|---|---|
path | string | String specifying the location of the Function |
Example of how to retrieve the file path for a Function
1exports.handler = function (context, event, callback) {2// Get the path for the Function. Note that the key of the function3// is not preceded by a "/" as is the case with Assets4const path = Runtime.getFunctions()['example-function'].path;56console.log('The path to your Function is: ' + path);78return callback();9};
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
:
Implement Zoltar and define an ask method
1exports.ask = () => {2// We're not totally sure if Zoltar's advice is all that helpful3const 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];1718// Generate a random index and return the given fortune19return 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:
Example of how to include code from other Functions
1exports.handler = function (context, event, callback) {2// First, get the path for the Function. Note that the key of the function3// is not preceded by a "/" as is the case with Assets4const zoltarPath = Runtime.getFunctions()['zoltar'].path;56// Next, use require() to import the library7const zoltar = require(zoltarPath);89// Finally, use the module as you would any other!10console.log('The answer to your riddle is: ' + zoltar.ask());1112return 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 name | Method name in Functions |
---|---|
syncMaps | maps |
syncLists | lists |
getSync
optionally accepts a configuration object with the following properties.
Parameter | Type | Description |
---|---|---|
serviceName | string | String specifying either the serviceSid or uniqueName of the Sync Service to connect to. Defaults to default . |
Example of how to get the default Sync Service Instance
1exports.handler = (context, event, callback) => {2// Use the getSync method with no arguments to get a reference to the default3// Sync document for your account. Fetch returns a Promise, which will4// eventually resolve to metadata about the Sync Service, such as its SID5Runtime.getSync()6.fetch()7.then((defaultSyncService) => {8console.log('Sync Service SID: ', defaultSyncService.sid);9return callback(null, defaultSyncService.sid);10})11.catch((error) => {12console.log('Sync Error: ', error);13return callback(error);14});15};
Example of how to use Runtime Client to get an Sync Service Instance by providing the SID
1exports.handler = (context, event, callback) => {2// Pass a serviceName to getSync to get a reference to that specific3// Sync document on your account. Fetch returns a Promise, which will4// eventually resolve to metadata about the Sync Service, such as friendlyName5Runtime.getSync({ serviceName: 'ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' })6.fetch()7.then((syncService) => {8console.log('Sync Service Name: ' + syncService.friendlyName);9return callback(null, syncService.friendlyName);10})11.catch((error) => {12console.log('Sync Error: ', error);13return callback(error);14});15};
Example of how to create a Map in Sync with the Runtime Client
1exports.handler = (context, event, callback) => {2// maps, which is a shortcut to syncMaps, allows you to create a new Sync Map3// instance. Be sure to provide a uniqueName identifier!4Runtime.getSync()5.maps.create({6uniqueName: 'spaceShips',7})8.then((newMap) => {9console.log(newMap);10return callback(null, newMap);11})12.catch((error) => {13console.log('Sync Error: ', error);14return callback(error);15});16};
Example of how to add an entry to a Sync Map with the Runtime Client
1exports.handler = (context, event, callback) => {2// Given an existing Sync Map with the uniqueName of spaceShips, you can use3// syncMapItems.create to add a new key:data pair which will be accessible4// to any other Function or product with access to the Sync Map!5Runtime.getSync()6.maps('spaceShips')7.syncMapItems.create({8key: 'fastestShip',9data: {10name: 'Millenium Falcon',11},12})13.then((response) => {14console.log(response);15return callback(null, response);16})17.catch((error) => {18console.log('Sync Error: ', error);19return callback(error);20});21};
Example of how to create Sync List with Runtime Client
1exports.handler = (context, event, callback) => {2// If your use case warrants a list data structure instead of a map, you3// can instantiate a Sync List. As with Maps, be sure to provide a uniqueName!4Runtime.getSync()5.lists.create({6uniqueName: 'spaceShips',7})8.then((newList) => {9console.log(newList);10return callback(null, newList);11})12.catch((error) => {13console.log('Sync Error: ', error);14return callback(error);15});16};
Example of how to append to a Sync List using the Runtime Client
1exports.handler = (context, event, callback) => {2// Given an existing Sync List with the uniqueName of spaceShips, you can use3// syncListItems.create to append a new data entry which will be accessible4// to any other Function or product with access to the Sync List!5Runtime.getSync()6.lists('spaceShips')7.syncListItems.create({8data: {9text: 'Millennium Falcon',10},11})12.then((response) => {13console.log(response);14return callback(null, response);15})16.catch((error) => {17console.log('Sync Error: ', error);18return callback(error);19});20};
Example of how to create a Sync Document using the Runtime Client
1exports.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.4Runtime.getSync()5.documents.create({6uniqueName: 'userPreferences',7data: {8greeting: 'Ahoyhoy!',9},10})11.then((newDoc) => {12console.log(newDoc);13return callback(null, newDoc);14})15.catch((error) => {16console.log('Sync Error: ', error);17return callback(error);18});19};
Example of creating a Sync Map and adding data to it in the same Function execution
1exports.handler = async (context, event, callback) => {2// Grab a reference to the Sync object since we'll be using it a few times3const sync = Runtime.getSync();45try {6// First, lets create a brand new Sync Map7const newMap = await sync.maps.create({ uniqueName: 'quicklyUpdatedMap' });8console.log('newMap: ', newMap);910// 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.13const newMapItem = await sync.maps(newMap.sid).syncMapItems.create({14key: 'fastestShip',15data: {16name: 'Millenium Falcon',17},18});1920// Now that we have a new item, let's log and return it.21console.log('newMapItem: ', newMapItem);22return callback(null, newMapItem);23} catch (error) {24// Be sure to log and return any errors that occur!25console.error('Sync Error: ', error);26return callback(error);27}28};