Class: Client

Client

Client for the Twilio Sync service.

new Twilio.Sync.Client(token [, options])

Parameters:
Name Type Argument Description
token String Twilio access token.
options Client#ClientOptions <optional>
Options to customize the Client.
Properties:
Name Type Description
connectionState Client#ConnectionState Contains current service connection state. Valid options are ['connecting', 'connected', 'disconnecting', 'disconnected', 'denied', 'error'].
Example
// Using NPM
var SyncClient = require('twilio-sync');
var syncClient = new SyncClient(token, { logLevel: 'debug' });

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

Members


<readonly> version :String

Current version of Sync client.
Type:
  • String

Methods


<async> document( [arg])

Read or create a Sync Document.
Parameters:
Name Type Argument Description
arg String | Client#OpenOptions <optional>
One of:
  • Unique name or SID identifying a Sync Document - opens a 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.
  • Client#OpenOptions object for more granular control.
  • Returns:
    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.
    Type
    Promise.<Document>
    Example
    syncClient.document('MyDocument')
      .then(function(document) {
        console.log('Successfully opened a Document. SID: ' + document.sid);
        document.on('updated', function(event) {
          console.log('Received updated event: ', event);
        });
      })
      .catch(function(error) {
        console.log('Unexpected error', error);
      });

    <async> instantQuery(indexName)

    For Flex customers only. Creates a query object that can be used to issue one-time queries repeatedly against the target index.
    Parameters:
    Name Type Description
    indexName String Must specify one of the Flex data classes for which Live Queries are available.
    Returns:
    a promise which resolves after the InstantQuery is successfully created.
    Type
    Promise.<InstantQuery>
    Example
    syncClient.instantQuery('tr-worker')
       .then(function(q) {
           q.on('searchResult', function(items) {
             Object.entries(items).forEach(([key, value]) => {
                console.log('Search result item key: ' + key);
                console.log('Search result item value: ' + value);
             });
          });
       });

    <async> list( [arg])

    Read or create a Sync List.
    Parameters:
    Name Type Argument Description
    arg String | Client#OpenOptions <optional>
    One of:
  • Unique name or SID identifying a Sync List - opens a 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.
  • Client#OpenOptions object for more granular control.
  • Returns:
    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.
    Type
    Promise.<List>
    Example
    syncClient.list('MyList')
      .then(function(list) {
        console.log('Successfully opened a List. SID: ' + list.sid);
        list.on('itemAdded', function(event) {
          console.log('Received itemAdded event: ', event);
        });
      })
      .catch(function(error) {
        console.log('Unexpected error', error);
      });

    <async> liveQuery(indexName, queryExpression)

    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.
    Parameters:
    Name Type Description
    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 Live Query Language page for Sync Client limits and full list of operators currently supported in query expressions.
    Returns:
    a promise that resolves when the query has been successfully executed.
    Type
    Promise.<LiveQuery>
    Example
    syncClient.liveQuery('tr-worker', 'data.attributes.worker_name == "Bob"')
        .then(function(args) {
           console.log('Subscribed to live data updates for worker Bob');
           let items = args.getItems();
           Object.entries(items).forEach(([key, value]) => {
             console.log('Search result item key: ' + key);
             console.log('Search result item value: ' + value);
           });
        })
        .catch(function(err) {
           console.log('Error when subscribing to live updates for worker Bob', err);
        });

    <async> map( [arg])

    Read or create a Sync Map.
    Parameters:
    Name Type Argument Description
    arg String | Client#OpenOptions <optional>
    One of:
  • Unique name or SID identifying a Sync Map - opens a 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.
  • Client#OpenOptions object for more granular control.
  • Returns:
    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.
    Type
    Promise.<Map>
    Example
    syncClient.map('MyMap')
      .then(function(map) {
        console.log('Successfully opened a Map. SID: ' + map.sid);
        map.on('itemUpdated', function(event) {
          console.log('Received itemUpdated event: ', event);
        });
      })
      .catch(function(error) {
        console.log('Unexpected error', error);
      });

    <async> stream( [arg])

    Read or create a Sync Message Stream.
    Parameters:
    Name Type Argument Description
    arg String | Client#OpenOptions <optional>
    One of:
  • Unique name or SID identifying a Stream - opens a 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.
  • Client#OpenOptions object for more granular control.
  • Returns:
    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.
    Type
    Promise.<Stream>
    Example
    syncClient.stream('MyStream')
      .then(function(stream) {
        console.log('Successfully opened a Message Stream. SID: ' + stream.sid);
        stream.on('messagePublished', function(event) {
          console.log('Received messagePublished event: ', event);
        });
      })
      .catch(function(error) {
        console.log('Unexpected error', error);
      });

    updateToken(token)

    Set new authentication token.
    Parameters:
    Name Type Description
    token String New token to set.
    Returns:
    Type
    Promise.<void>

    Type Definitions


    ClientOptions

    These options can be passed to Client constructor.
    Type:
    • Object
    Properties:
    Name Type Argument Default Description
    logLevel String <optional>
    'error' The level of logging to enable. Valid options (from strictest to broadest): ['silent', 'error', 'warn', 'info', 'debug', 'trace'].

    ConnectionState

    Indicates current state of connection between the client and Sync service.

    Valid options are as follows:

  • 'connecting' - client is offline and connection attempt is in process.
  • 'connected' - client is online and ready.
  • 'disconnecting' - client is going offline as disconnection is in process.
  • 'disconnected' - client is offline and no connection attempt is in process.
  • 'denied' - client connection is denied because of invalid JWT access token. User must refresh token in order to proceed.
  • 'error' - client connection is in a permanent erroneous state. Client re-initialization is required.
  • Type:
    • 'connecting' | 'connected' | 'disconnecting' | 'disconnected' | 'denied' | 'error'

    OpenOptions

    Options for opening a Sync Object.
    Type:
    • Object
    Properties:
    Name Type Argument Default Description
    id String <optional>
    Sync object SID or unique name.
    mode 'open_or_create' | 'open_existing' | 'create_new' <optional>
    'open_or_create' The mode for opening the Sync object:
  • 'open_or_create' - reads a Sync object or creates one if it does not exist.
  • 'open_existing' - reads an existing Sync object. The promise is rejected if the object does not exist.
  • 'create_new' - creates a new Sync object. If the id property is specified, it will be used as the unique name.
  • ttl Number <optional>
    The time-to-live of the Sync object in seconds. This is applied only if the object is created.
    value Object <optional>
    { } The initial value for the Sync Document (only applicable to Documents).
    Example

    The following example is applicable to all Sync objects (i.e., syncClient.document(), syncClient.list(), syncClient.map(), syncClient.stream())

    // Attempts to open an existing Document with unique name 'MyDocument'
    // If no such Document exists, the promise is rejected
    syncClient.document({
        id: 'MyDocument',
        mode: 'open_existing'
      })
      .then(...)
      .catch(...);
    
    // Attempts to create a new Document with unique name 'MyDocument', TTL of 24 hours and initial value { name: 'John Smith' }
    // If such a Document already exists, the promise is rejected
    syncClient.document({
        id: 'MyDocument',
        mode: 'create_new',
        ttl: 86400
        value: { name: 'John Smith' } // the `value` property is only applicable for Documents
      })
      .then(...)
      .catch(...);

    Events


    connectionError

    Fired when connection is interrupted by unexpected reason
    Properties:
    Name Type Description
    error Object connection error details
    Properties
    Name Type Argument Description
    terminal Boolean twilsock will stop connection attempts
    message String root cause
    httpStatusCode Number <optional>
    http status code if available
    errorCode Number <optional>
    Twilio public error code if available
    Example
    syncClient.on('connectionError', function(connectionError) {
      console.log('Connection was interrupted: ' + connectionError.message +
        ' (isTerminal: ' + connectionError.terminal')');
    });

    connectionStateChanged

    Fired when connection state has been changed.
    Parameters:
    Name Type Description
    connectionState Client#ConnectionState Contains current service connection state.
    Example
    syncClient.on('connectionStateChanged', function(newState) {
      console.log('Received new connection state: ' + newState);
    });

    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 tokenExpired events occur; handling just one of them is sufficient.
    Type: void
    Example

    The following example illustrates access token refresh

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

    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 tokenExpired events occur; handling just one of them is sufficient.
    Type: void