Menu

Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

TaskRouter.js TaskQueue: Managing a TaskQueue resource in the browser

The SDK allows developers to interact with the entire TaskRouter REST API by a simple JS API.

Adding the SDK to your application

Include the TaskRouter JS SDK in your JavaScript application as follows:

<script type="text/javascript" src="//media.twiliocdn.com/taskrouter/js/v1.13/taskrouter.min.js"></script>

Creating a TaskRouter TaskQueue capability token

TaskRouter uses Twilio capability tokens to delegate scoped access to TaskRouter resources to your JavaScript application. Twilio capability tokens conform to the JSON Web Token (commonly referred to as a JWT and pronounced "jot") standard, which allow for limited-time use of credentials by a third party. Your web server needs to generate a Twilio capability token and provide it to your JavaScript application in order to register a TaskRouter TaskQueue.

We provide three relevant helper methods to provide access capabilities:

Capability Authorization
AllowFetchSubresources A TaskQueue can fetch any subresource (statistics)
AllowUpdates A TaskQueue can update its properties
AllowDelete A TaskQueue can delete itself

Additionally, you can utilize more granular access to particular resources beyond these capabilities. These can viewed under Constructing JWTs.

You can generate a TaskRouter capability token using any of Twilio's Helper Libraries. You'll need to provide your Twilio AccountSid and AuthToken, the WorkspaceSid the TaskQueue belongs to and the TaskQueueSid you would like to register. For example, using our PHP helper library you can create a token and add capabilities as follows:

Loading Code Sample...
      
      
      
      

      Once you have generated a TaskRouter capability token, you can pass this to your front-end web application and intialize the JavaScript library as follows:

      var taskQueue = new Twilio.TaskRouter.TaskQueue(TASKQUEUE_TOKEN);
      

      The library will raise a 'ready' event once it has connected to TaskRouter:

      taskQueue.on("ready", function(taskQueue) {
        console.log(taskQueue.sid)                // 'WQxxx'
        console.log(taskQueue.friendlyName)       // 'Simple FIFO Queue'
        console.log(taskQueue.targetWorkers)      // '1==1'
        console.log(taskQueue.maxReservedWorkers) // 20
      });
      

      See more about the methods and events exposed on this object below.

      TaskQueue API

      TaskRouter.js TaskQueue exposes the following API:

      Twilio.TaskRouter.TaskQueue

      Twilio.TaskRouter.TaskQueue is the top-level class you'll use for managing a TaskQueue.

      new Twilio.TaskRouter.TaskQueue(taskQueueToken)

      Register a new Twilio.TaskRouter.TaskQueue with the capabilities provided in taskQueueToken.

      Parameters

      Name Type Description
      taskQueueToken String A Twilio TaskRouter capability token. See Creating a TaskRouter capability token for more information.
      debug Boolean (optional) Whether or not the JS SDK will print event messages to the console. Defaults to true.

      Sample usage

      var taskQueue = new Twilio.TaskRouter.TaskQueue(TASKQUEUE_TOKEN);
      

      Turning off debugging:

      var taskQueue = new Twilio.TaskRouter.TaskQueue(TASKQUEUE_TOKEN, false);
      

      Methods

      update([args...], [resultCallback])

      Updates a single or list of properties on a TaskQueue.

      Parameters

      Name Type Description
      args... String or JSON A single API parameter and value or a JSON object containing multiple values
      resultCallback Function (optional) A JavaScript Function that will be called with the result of the update. If an error occurs, the first argument passed to this function will be an Error. If the update is successful, the first argument will be null and the second argument will contain the updated TaskQueue.
      Single Attribute Example
      taskQueue.update("MaxReservedWorkers", "20", function(error, taskQueue) {
        if(error) {
          console.log(error.code);
          console.log(error.message);
        } else {
          console.log(taskQueue.maxReservedWorkers); // 20
        }
      });
      
      Multiple Attribute Example
      var targetWorkers = "languages HAS \"english\"";
      var props = {"MaxReservedWorkers", "20", "TargetWorkers":targetWorkers};
      taskQueue.update(props, function(error, workspace) {
        if(error) {
          console.log(error.code);
          console.log(error.message);
        } else {
          console.log(taskQueue.maxReservedWorkers); // "20"
          console.log(taskQueue.targetWorkers); // "languages HAS "english""
        }
      });
      

      delete([resultCallback])

      Deletes a TaskQueue

      Parameters

      Name Type Description
      resultCallback Function (optional) A JavaScript Function that will be called with the result of the delete. If an error occurs, the first argument passed to this function will be an Error. If the delete is successful, the first argument will be null.

      Example

      taskQueue.delete(function(error) {
        if(error) {
          console.log(error.code);
          console.log(error.message);
        } else {
          console.log("taskQueue deleted");
        }
      });
      

      updateToken(taskQueueToken)

      Updates the TaskRouter capability token for the Workspace.

      Parameters

      Name Type Description
      taskQueueToken String A valid TaskRouter capability token.
      Example
      var token = refreshJWT(); // your method to retrieve a new capability token
      taskQueue.updateToken(token);
      

      statistics

      Retrieves the object to retrieve the statistics for a TaskQueue.

      fetch

      Parameters

      Name Type Description
      params JSON (optional) A JSON object of query parameters
      callback Function A function that will be called when the statistics object is returned. If an error occurs when retrieving the list, the first parameter passed to this function will contain the Error object. If the retrieval is successful, the first parameter will be null and the second parameter will contain a statistics object.
      var queryParams = {"Minutes":"240"}; // 4 hours
      taskQueue.statistics.fetch(
          queryParams,
          function(error, statistics) {
              if(error) {
                  console.log(error.code);
                  console.log(error.message);
                  return;
              }
              console.log("fetched taskQueue statistics: "+JSON.stringify(statistics));
              console.log("avg task acceptance time: "+statistics.cumulative.avgTaskAcceptanceTime;
          }
      );
      

      cumulative statistics

      If you only care about the cumulative stats for a TaskQueue for a given time period, you can utilize this instead of the above for a smaller payload and faster response time.

      fetch

      Parameters

      Name Type Description
      params JSON (optional) A JSON object of query parameters
      callback Function A function that will be called when the statistics object is returned. If an error occurs when retrieving the list, the first parameter passed to this function will contain the Error object. If the retrieval is successful, the first parameter will be null and the second parameter will contain a statistics object.
      var queryParams = {"Minutes":"240"}; // 4 hours
      taskQueue.cumulativeStats.fetch(
          queryParams,
          function(error, statistics) {
              if(error) {
                  console.log(error.code);
                  console.log(error.message);
                  return;
              }
              console.log("fetched taskQueue statistics: "+JSON.stringify(statistics));
              console.log("avg task acceptance time: "+statistics.avgTaskAcceptanceTime;
          }
      );
      

      real time statistics

      If you only care about the realtime stats for a TaskQueue for a given time period, you can utilize this instead of the above for a smaller payload and faster response time.

      fetch

      Parameters

      Name Type Description
      params JSON (optional) A JSON object of query parameters
      callback Function A function that will be called when the statistics object is returned. If an error occurs when retrieving the list, the first parameter passed to this function will contain the Error object. If the retrieval is successful, the first parameter will be null and the second parameter will contain a statistics object.
      taskQueue.realtimeStats.fetch(
          function(error, statistics) {
              if(error) {
                  console.log(error.code);
                  console.log(error.message);
                  return;
              }
              console.log("fetched taskQueue statistics: "+JSON.stringify(statistics));
              console.log("total available workers: "+statistics.totalAvailableWorkers;
              console.log("total eligible workers: "+statistics.totalEligibleWorkers;
          }
      );
      

      on(event, callback)

      Attaches a listener to the specified event. See Events for the complete list of supported events.

      Parameters

      Name Type Description
      event String An event name. See Events for the complete list of supported events.
      callback Function A function that will be called when the specified Event is raised.

      Example

      taskQueue.on("ready", function(taskQueue) {
          console.log(taskQueue.friendlyName)      // My TaskQueue
      });
      

      Events

      TaskRouter's JS library currently raises the following events to the registered TaskQueue:

      ready

      The TaskQueue has established a connection to TaskRouter and has completed initialization.

      Parameters

      Name Type Description
      taskQueue TaskQueue The created TaskQueue.

      Example

      taskQueue.on("ready", function(taskQueue) {
          console.log(taskQueue.friendlyName)      // My TaskQueue
      });
      

      connected

      The TaskQueue has established a connection to TaskRouter.

      Example

      taskQueue.on("connected", function() {
          console.log("Websocket has connected");
      });
      

      disconnected

      The TaskQueue has disconnected a connection from TaskRouter.

      Example

      taskQueue.on("disconnected", function() {
          console.log("Websocket has disconnected");
      });
      

      token.expired

      Raised when the TaskRouter capability token used to create this TaskQueue expires.

      Example

      taskQueue.on("token.expired", function() {
          console.log("updating token");
          var token = refreshJWT(); // your method to retrieve a new capability token
          taskQueue.updateToken(token);
      });
      

      Need some help?

      We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

      Loading Code Sample...