Creating a Twilio library in CoffeeScript
A library is only as good as its ability to get out of the way when you are coding with it. I decided to test the capabilities of CoffeeScript by using it to create a library for Twilio. I chose Twilio's Java library to port because it is expressly object-oriented.
One of the interesting challenges I had to handle in porting the library was overloaded constructors. You can only create a single constructor but you can use splats to indicate a variable number of function properties or explicitly check for existence to handle multiple cases. For the Dial class, I needed to handle either zero or one parameters.
constructor: (number) ->
v = new VerbConstants()
super(v.DIAL, number)
if number isnt undefined
super(v.DIAL, null)
if number is undefined
@allowedVerbs = [ ]
@allowedVerbs.push(v.NUMBER)
@allowedVerbs.push(v.CONFERENCE)
It checks to see if number is undefined and if so, it executes the equivalent of the no-arg Java constructor.
For the TwilioRestClient class, I took the slightly easier route by using the built-in httpclient support from Jetty. That way, I didn't have to worry about base64 encoding or setting the Authorization request header.
httpclient = require "ringo/httpclient"
class TwilioRestClient
constructor: (accountSid, authToken, endpoint) ->
@accountSid = accountSid
@authToken = authToken
@endpoint = "https://api.twilio.com/2010-04-01/Accounts/#{@accountSid}"
request: (path, method, vars) ->
try
response = httpclient.request({
method: method,
username: @accountSid,
password: @authToken,
data: vars
url: @endpoint + path + ".json"
})
catch error
print error
exports.TwilioRestClient = TwilioRestClient
RingoJS
To keep with the Java spirit, I decided to use RingoJS, a Java server-side web framework using Rhino(JavaScript on the JVM). RingoJS lets you use JS but consume from the buffet of Java libraries. Ringo can be deployed on any Java server including Google App Engine.
Installing and Running the Twilio Code
After downloading RingoJS and compiling the Twilio code into JavaScript, follow the instructions on the github page. To run the app server, run
ringo <path to twilio example code>/main.js
You can then navigate to localhost:8080 and make a REST call to make a phone call. Make sure to add you credentials and from phone number to the makeCall function in actions.js. We could also execute an individual script. The example code drop has scripts for making a call(make_call.js), shown below, and creating the TwiML for a conference(conference.js).
var twilio = require("twilio/TwilioRestClient")
// Makes a call
var client = new twilio.TwilioRestClient("<accountSid>","<authToken>",null);
var response = client.request("/Calls","POST",{
To:"15553241111",
From:"15553241112",
Url:"http://demo.twilio.com/welcome"
})
print(response.content)
RingoJS http://ringojs.org/
Twilio-CoffeeScript https://github.com/jwill/twilio-coffeescript
Twilio http://www.twilio.com