Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

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


(information)

Info

The following documentation is for the JS SDK V1(link takes you to an external page). If you're working with the Twilio Flex SDK, head over to the TaskRouter.js documentation on Github(link takes you to an external page).

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


Adding the SDK to your application

adding-the-sdk-to-your-application page anchor

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


_10
<script src="https://sdk.twilio.com/js/taskrouter/v1.21/taskrouter.min.js" integrity="sha384-5fq+0qjayReAreRyHy38VpD3Gr9R2OYIzonwIkoGI4M9dhfKW6RWeRnZjfwSrpN8" crossorigin="anonymous"></script>

Creating a TaskRouter TaskQueue capability token

capability-token page anchor

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:

CapabilityAuthorization
AllowFetchSubresourcesA TaskQueue can fetch any subresource (statistics)
AllowUpdatesA TaskQueue can update its properties
AllowDeleteA 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:

Creating a TaskRouter TaskQueue capability token

creating-a-taskrouter-taskqueue-capability-token page anchor
Node.js
Python
C#
Java
PHP
Ruby

_59
// Download the Node helper library from twilio.com/docs/node/install
_59
// These consts are your accountSid and authToken from https://www.twilio.com/console
_59
const taskrouter = require('twilio').jwt.taskrouter;
_59
_59
const TaskRouterCapability = taskrouter.TaskRouterCapability;
_59
const Policy = TaskRouterCapability.Policy;
_59
_59
// To set up environmental variables, see http://twil.io/secure
_59
const accountSid = process.env.TWILIO_ACCOUNT_SID;
_59
const authToken = process.env.TWILIO_AUTH_TOKEN;
_59
const workspaceSid = 'WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
_59
const taskqueueSid = 'WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
_59
_59
const TASKROUTER_BASE_URL = 'https://taskrouter.twilio.com';
_59
const version = 'v1';
_59
_59
// By default, tokens are good for one hour.
_59
// Override this default timeout by specifiying a new value (in seconds).
_59
// For example, to generate a token good for 8 hours:
_59
const ttl = 28800; // 60 * 60 * 8
_59
_59
const capability = new TaskRouterCapability({
_59
accountSid: accountSid,
_59
authToken: authToken,
_59
workspaceSid: workspaceSid,
_59
channelId: taskqueueSid,
_59
ttl: ttl,
_59
});
_59
_59
// Helper function to create Policy
_59
function buildWorkspacePolicy(options) {
_59
options = options || {};
_59
const resources = options.resources || [];
_59
const urlComponents = [
_59
TASKROUTER_BASE_URL,
_59
version,
_59
'Workspaces',
_59
workspaceSid,
_59
];
_59
_59
return new Policy({
_59
url: urlComponents.concat(resources).join('/'),
_59
method: options.method || 'GET',
_59
allow: true,
_59
});
_59
}
_59
_59
const allowFetchSubresources = buildWorkspacePolicy({
_59
resources: ['TaskQueue', taskqueueSid, '**']
_59
});
_59
const allowUpdates = buildWorkspacePolicy({
_59
resources: ['TaskQueue', taskqueueSid],
_59
method: 'POST',
_59
});
_59
_59
capability.addPolicy(allowFetchSubresources);
_59
capability.addPolicy(allowUpdates);
_59
_59
const token = capability.toJwt();

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


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

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


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

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


TaskRouter.js TaskQueue exposes the following API:


Twilio.TaskRouter.TaskQueue

taskroutertaskqueue page anchor

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

new Twilio.TaskRouter.TaskQueue(taskQueueToken)

new-taskroutertaskqueue page anchor

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

NameTypeDescription
taskQueueTokenStringA Twilio TaskRouter capability token. See Creating a TaskRouter capability token for more information.
debugBoolean(optional) Whether or not the JS SDK will print event messages to the console. Defaults to true.
regionString(optional) A Twilio region for websocket connections (ex. ie1-ix).
maxRetriesInteger(optional) The maximum of retries to attempt if a websocket request fails. Defaults to 0.

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

Turning off debugging:


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

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

update page anchor

Updates a single or list of properties on a TaskQueue.

NameTypeDescription
args...String or JSONA single API parameter and value or a JSON object containing multiple values
resultCallbackFunction(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
single-attribute-example page anchor

_10
taskQueue.update("MaxReservedWorkers", "20", function(error, taskQueue) {
_10
if(error) {
_10
console.log(error.code);
_10
console.log(error.message);
_10
} else {
_10
console.log(taskQueue.maxReservedWorkers); // 20
_10
}
_10
});

Multiple Attribute Example
multiple-attribute-example page anchor

_11
var targetWorkers = "languages HAS \"english\"";
_11
var props = {"MaxReservedWorkers", "20", "TargetWorkers":targetWorkers};
_11
taskQueue.update(props, function(error, workspace) {
_11
if(error) {
_11
console.log(error.code);
_11
console.log(error.message);
_11
} else {
_11
console.log(taskQueue.maxReservedWorkers); // "20"
_11
console.log(taskQueue.targetWorkers); // "languages HAS "english""
_11
}
_11
});

delete([resultCallback])

delete page anchor

Deletes a TaskQueue

NameTypeDescription
resultCallbackFunction(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.

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

updateToken(taskQueueToken)

updatetoken page anchor

Updates the TaskRouter capability token for the Workspace.

NameTypeDescription
taskQueueTokenStringA valid TaskRouter capability token.

_10
var token = refreshJWT(); // your method to retrieve a new capability token
_10
taskQueue.updateToken(token);

Retrieves the object to retrieve the statistics for a TaskQueue.

NameTypeDescription
paramsJSON(optional) A JSON object of query parameters
callbackFunctionA 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.

_13
var queryParams = {"Minutes":"240"}; // 4 hours
_13
taskQueue.statistics.fetch(
_13
queryParams,
_13
function(error, statistics) {
_13
if(error) {
_13
console.log(error.code);
_13
console.log(error.message);
_13
return;
_13
}
_13
console.log("fetched taskQueue statistics: "+JSON.stringify(statistics));
_13
console.log("avg task acceptance time: "+statistics.cumulative.avgTaskAcceptanceTime;
_13
}
_13
);

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.

NameTypeDescription
paramsJSON(optional) A JSON object of query parameters
callbackFunctionA 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.

_13
var queryParams = {"Minutes":"240"}; // 4 hours
_13
taskQueue.cumulativeStats.fetch(
_13
queryParams,
_13
function(error, statistics) {
_13
if(error) {
_13
console.log(error.code);
_13
console.log(error.message);
_13
return;
_13
}
_13
console.log("fetched taskQueue statistics: "+JSON.stringify(statistics));
_13
console.log("avg task acceptance time: "+statistics.avgTaskAcceptanceTime;
_13
}
_13
);

real time statistics

realtimestatistics page anchor

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.

NameTypeDescription
paramsJSON(optional) A JSON object of query parameters
callbackFunctionA 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.

_12
taskQueue.realtimeStats.fetch(
_12
function(error, statistics) {
_12
if(error) {
_12
console.log(error.code);
_12
console.log(error.message);
_12
return;
_12
}
_12
console.log("fetched taskQueue statistics: "+JSON.stringify(statistics));
_12
console.log("total available workers: "+statistics.totalAvailableWorkers;
_12
console.log("total eligible workers: "+statistics.totalEligibleWorkers;
_12
}
_12
);

on(event, callback)

taskqueue-on page anchor

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

NameTypeDescription
eventStringAn event name. See Events for the complete list of supported events.
callbackFunctionA function that will be called when the specified Event is raised.

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


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

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

NameTypeDescription
taskQueueTaskQueueThe created TaskQueue.

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

The TaskQueue has established a connection to TaskRouter.


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

The TaskQueue has disconnected a connection from TaskRouter.


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

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


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


Rate this page: