Skip to content

Node Version 3.x Upgrade Guide

Jingming Niu edited this page Mar 25, 2016 · 5 revisions

This is an upgrade guide for moving from 2.x to 3.x versions of the twilio-node helper library.

Import

In twilio-node 2.x, you would have to make a new instance of each client you used:

var Twilio = require('twilio');

var ipmClient = new Twilio.IpMessagingClient(USERNAME, PASSWORD);
var lookupsClient = new Twilio.LookupsClient(USERNAME, PASSWORD);

Now, in twilio-node 3.x, there is only 1 object to import and initialize:

var Twilio = require('twilio');
var twilio = new Twilio(USERNAME, PASSWORD);

Accessing Resources

Listing Resources

There are now 2 ways to get a list of resources: list and each.

  • list will fetch the entire collection of resources and resolves to an array that contains the resources instances.
var promise = twilio.messages.list();
promise.then(function(messages) {
  console.log(messages);
});
// [MessageInstance, MessageInstance, MessageInstance, ...]
  • each will page through the list of resources and call the callback function that you passed in with each instance and a done function. To stop iteration at any point, call the done function.
twilio.messages.each(function(message) {
  console.log(message.sid);
});
// 'SM123'

var i = 0;
twilio.messages.each(function(message, done) {
  console.log(message.sid);

  i++;
  
  // break after 10 messages
  if (i >= 10) {
    done();
  }
});

Paging

One of the biggest advantages of twilio-node 3.x is that it automatically handles paging for you! In both list and stream, you can specify the maximum number of instances to grab (limit), and the page size (pageSize). The library will take care of everything else.

twilio.messages.each(function(message) {
  console.log(message.sid);
});
var promise = twilio.messages.list();
promise.then(function(messages) {
  console.log(messages.length);
});
// 125

promise = twilio.messages.list({
  limit: 100
});
promise.then(function(messages) {
  console.log(messages.length);
});
// 100

Proper Types

Configurable HTTP Client

You can now plug your own HTTP client into the Twilio client! Just pass a client that conforms to the RequestClient interface and pass it in when you initialize Twilio.

var client = new CustomClient();
var twilio = new Twilio(USERNAME, PASSWORD, client);
Clone this wiki locally