Options
All
  • Public
  • Public/Protected
  • All
Menu

Client for the Twilio Sync service.

example
// Using NPM resolution
const SyncClient = require('twilio-sync');
const syncClient = new SyncClient(token, { loglevel: 'debug' });

// Using CDN
const syncClient = new Twilio.Sync.Client(token, { logLevel: 'debug' });

Hierarchy

  • EventEmitter
    • SyncClient

Index

Constructors

constructor

  • Parameters

    • fpaToken: string

      Twilio access token.

    • options: SyncClientOptions = {}

      Options to customize the client.

    Returns SyncClient

Events

Static Readonly connectionError

connectionError: "connectionError" = 'connectionError'

Fired when connection is interrupted by unexpected reason.

Parameters:

  1. object connectionError - connection error details. It has following properties:
    • boolean terminal - twilsock will stop connection attempts
    • string message - root cause
    • number? httpStatusCode - HTTP status code if available
    • number? errorCode - Twilio public error code if available
example
syncClient.on('connectionError', (connectionError) => {
  console.error('Connection was interrupted:', connectionError.message);
  console.error('Is terminal:', connectionError.terminal);
});

Static Readonly connectionStateChanged

connectionStateChanged: "connectionStateChanged" = 'connectionStateChanged'

Fired when connection state has been changed.

Parameters:

  1. ConnectionState connectionState - contains current service connection state.
example
syncClient.on('connectionStateChanged', (newState) => {
  console.log('Received a new connection state:', newState);
});

Static Readonly tokenAboutToExpire

tokenAboutToExpire: "tokenAboutToExpire" = 'tokenAboutToExpire'

Fired when the access token is about to expire and needs to be updated. The trigger takes place three minutes before the JWT access token expiry. For long living applications, you should refresh the token when either tokenAboutToExpire or tokenExpire events occur; handling just one of them is sufficient.

example

The following example illustrates access token refresh.

syncClient.on('tokenAboutToExpire', () => {
  // Obtain a JWT access token: https://www.twilio.com/docs/sync/identity-and-access-tokens
  const token = '<your-access-token-here>';
  syncClient.updateToken(token);
});

Static Readonly tokenExpired

tokenExpired: "tokenExpired" = 'tokenExpired'

Fired when the access token is expired. In case the token is not refreshed, all subsequent Sync operations will fail and the client will disconnect. For long living applications, you should refresh the token when either tokenAboutToExpire or tokenExpire events occur; handling just one of them is sufficient.

Accessors

connectionState

  • get connectionState(): ConnectionState
  • Current service connection state.

    Returns ConnectionState

Static version

  • get version(): string
  • Current version of the Sync client.

    Returns string

Methods

document

  • Read or create a Sync document.

    example
    syncClient.document('MyDocument')
      .then((document) => {
        console.log('Successfully opened a document. SID:', document.sid);
        document.on('updated', (event) => {
          console.log('Received an "updated" event: ', event);
        });
      })
      .catch((error) => {
        console.error('Unexpected error', error);
      });
    

    Parameters

    • Optional arg: string | OpenDocumentOptions

      Could be any of the following:

      • Unique name or SID identifying the Sync document - opens the document with the given identifier or creates one if it does not exist.
      • none - creates a new document with a randomly assigned SID and no unique name.
      • OpenDocumentOptions object for more granular control.

    Returns Promise<SyncDocument>

    A promise which resolves after the document is successfully read (or created). This promise may reject if the document could not be created or if this endpoint lacks the necessary permissions to access it.

instantQuery

  • For Flex customers only. Creates a query object that can be used to issue one-time queries repeatedly against the target index.

    example
    syncClient.instantQuery('tr-worker')
      .then((q) => {
        q.on('searchResult', (items) => {
          Object.entries(items).forEach(([key, value]) => {
            console.log('Search result item key:', key);
            console.log('Search result item value:', value);
          });
        });
      });
    

    Parameters

    • indexName: string

      Must specify one of the Flex data classes for which live queries are available.

    Returns Promise<InstantQuery>

    A promise which resolves after the instance of InstantQuery is successfully created.

list

  • Read or create a Sync list.

    example
    syncClient.list('MyList')
      .then((list) => {
        console.log('Successfully opened a List. SID:', list.sid);
        list.on('itemAdded', (event) => {
          console.log('Received an "itemAdded" event:', event);
        });
      })
      .catch((error) => {
        console.error('Unexpected error', error);
      });
    

    Parameters

    • Optional arg: string | OpenListOptions

      Could be any of the following:

      • Unique name or SID identifying a Sync list - opens the list with the given identifier or creates one if it does not exist.
      • none - creates a new list with a randomly assigned SID and no unique name.
      • OpenListOptions object for more granular control.

    Returns Promise<SyncList>

    A promise which resolves after the list is successfully read (or created). This promise may reject if the list could not be created or if this endpoint lacks the necessary permissions to access it.

liveQuery

  • liveQuery(indexName: string, queryExpression: string): Promise<LiveQuery>
  • For Flex customers only. Establishes a long-running query against Flex data wherein the returned result set is updated whenever new (or updated) records match the given expression. Updated results are presented row-by-row according to the lifetime of the returned LiveQuery object.

    example
    syncClient.liveQuery('tr-worker', 'data.attributes.worker_name == "Bob"')
      .then((args) => {
         console.log('Subscribed to live data updates for worker Bob');
         const items = args.getItems();
         Object.entries(items).forEach(([key, value]) => {
           console.log('Search result item key:', key);
           console.log('Search result item value:', value);
         });
      })
      .catch((err) => {
         console.error('Error when subscribing to live updates for worker Bob', err);
      });
    

    Parameters

    • indexName: string

      Must specify one of the Flex data classes for which Live Queries are available.

    • queryExpression: string

      A query expression to be executed against the given data index. Please review the Live Query Language page for Sync client limits and a full list of operators currently supported in query expressions.

    Returns Promise<LiveQuery>

    A promise that resolves when the query has been successfully executed.

map

  • Read or create a Sync map.

    example
    syncClient.map('MyMap')
      .then((map) => {
        console.log('Successfully opened a map. SID:', map.sid);
        map.on('itemUpdated', (event) => {
          console.log('Received an "itemUpdated" event:', event);
        });
      })
      .catch((error) => {
        console.error('Unexpected error', error);
      });
    

    Parameters

    • Optional arg: string | OpenMapOptions

      Could be any of the following:

      • Unique name or SID identifying the Sync map - opens the map with the given identifier or creates one if it does not exist.
      • none - creates a new map with a randomly assigned SID and no unique name.
      • OpenMapOptions object for more granular control.

    Returns Promise<SyncMap>

    A promise which resolves after the map is successfully read (or created). This promise may reject if the map could not be created or if this endpoint lacks the necessary permissions to access it.

shutdown

  • shutdown(): Promise<void>
  • Gracefully shuts the Sync client down.

    Returns Promise<void>

stream

  • Read or create a Sync message stream.

    example
    syncClient.stream('MyStream')
      .then((stream) => {
        console.log('Successfully opened a message stream. SID:', stream.sid);
        stream.on('messagePublished', (event) => {
          console.log('Received a "messagePublished" event:', event);
        });
      })
      .catch((error) => {
        console.error('Unexpected error', error);
      });
    

    Parameters

    • Optional arg: string | OpenStreamOptions

      Could be any of the following:

      • Unique name or SID identifying a stream - opens the stream with the given identifier or creates one if it does not exist.
      • none - creates a new stream with a randomly assigned SID and no unique name.
      • OpenStreamOptions object for more granular control.

    Returns Promise<SyncStream>

    A promise which resolves after the stream is successfully read (or created). The flow of messages will begin imminently (but not necessarily immediately) upon resolution. This promise may reject if the stream could not be created or if this endpoint lacks the necessary permissions to access it.

updateToken

  • updateToken(token: string): Promise<void>
  • Set the authentication token.

    Parameters

    • token: string

      New token to set.

    Returns Promise<void>