-
Notifications
You must be signed in to change notification settings - Fork 8
/
RestClient.gs
163 lines (141 loc) · 6.25 KB
/
RestClient.gs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
//REST API Config Defaults
var defaultHost = 'api.twilio.com',
defaultApiVersion = '2010-04-01';
/**
The Twilio REST API client
@constructor
@param {string} sid - The application SID, as seen in the Twilio portal
@param {string} tkn - The auth token, as seen in the Twilio portal
@param {object} options (optional) - optional config for the REST client
- @member {string} host - host for the Twilio API (default: api.twilio.com)
- @member {string} apiVersion - the Twilio REST API version to use for requests (default: 2010-04-01)
*/
function RestClient(sid, tkn, options) {
//Required client config
if (!sid || !tkn) {
if (process.env.TWILIO_ACCOUNT_SID && process.env.TWILIO_AUTH_TOKEN) {
this.accountSid = process.env.TWILIO_ACCOUNT_SID;
this.authToken = process.env.TWILIO_AUTH_TOKEN;
}
else {
throw 'RestClient requires an Account SID and Auth Token set explicitly ' +
'or via the TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN environment variables';
}
}
else {
//if auth token/SID passed in manually, trim spaces
this.accountSid = sid.replace(/ /g,'');
this.authToken = tkn.replace(/ /g,'');
}
//Optional client config
options = options || {};
this.host = options.host || defaultHost;
this.apiVersion = options.apiVersion || defaultApiVersion;
//REST Resource - shorthand for just "account" and "accounts" to match the REST API
var accountResource = Accounts_(this);
this.accounts = accountResource;
//mix the account object in with the client object - assume master account for resources
_.extend(this,accountResource);
//SMS shorthand
this.sendSms = this.accounts.sms.messages.post;
this.listSms = this.accounts.sms.messages.get;
this.getSms = function(messageSid, callback) {
this.accounts.sms.messages(messageSid).get(callback);
};
//Calls shorthand
this.makeCall = this.accounts.calls.post;
this.listCalls = this.accounts.calls.get;
this.getCall = function(callSid, callback) {
this.accounts.calls(callSid).get(callback);
};
}
/**
Get the base URL which we'll use for all requests with this client
@returns {string} - the API base URL
*/
RestClient.prototype.getBaseUrl = function () {
//Nodejs version
//return 'https://' + this.accountSid + ':' + this.authToken + '@' + this.host + '/' + this.apiVersion;
//GAS version without sid and token, because we're passing them inside the headers
return 'https://' + this.host + '/' + this.apiVersion;
};
/**
Make an authenticated request against the Twilio backend. Uses the request library,
and largely passes through to its API for options:
https://github.com/mikeal/request
@param {object} options - options for HTTP request
@param {function} callback - callback function for when request is complete
- @param {object} error - an error object if there was a problem processing the request
- @param {object} data - the JSON-parsed data
- @param {http.ClientResponse} response - the raw node http.ClientResponse object
*/
RestClient.prototype.request = function (options, callback) {
var client = this;
//Prepare request options
options.url = client.getBaseUrl() + options.url + '.json';
// options.headers = {
// 'Accept':'application/json',
// //'User-Agent':'twilio-node/' + moduleinfo.version
// };
//Initiate HTTP request
//******************
//HEADS UP ! added "client" parameter to request fonction beacause we need access
// to sid and token to make our "Authorization : Basic" header
//******************
request(client, options, function (err, response, body) {
if (callback) {
var data;
try {
data = err || !body ? {status: 500, message: 'Empty body'} : JSON.parse(body);
} catch (e) {
data = { status: 500, message: (e.message || 'Invalid JSON body') };
}
//request doesn't think 4xx is an error - we want an error for any non-2xx status codes
var error = null;
if (err || (response && (response.statusCode < 200 || response.statusCode > 206))) {
error = {};
// response is null if server is unreachable
if (response) {
error.status = response.statusCode;
error.message = data ? data.message : 'Unable to complete HTTP request';
error.code = data && data.code;
error.moreInfo = data && data.more_info;
} else {
error.status = err.code;
error.message = err.message;
}
}
//process data and make available in a more JavaScripty format
function processKeys(source) {
if (_.isObject(source)) {
Object.keys(source).forEach(function(key) {
//Supplement underscore values with camel-case
if (key.indexOf('_') > 0) {
var cc = key.replace(/_([a-z])/g, function (g) {
return g[1].toUpperCase()
});
source[cc] = source[key];
}
//process any nested arrays...
if (Array.isArray(source[key])) {
source[key].forEach(processKeys);
}
else if (_.isObject(source[key])) {
processKeys(source[key]);
}
});
//Look for and convert date strings for specific keys
['startDate', 'endDate', 'dateCreated', 'dateUpdated', 'startTime', 'endTime'].forEach(function(dateKey) {
if (source[dateKey]) {
source[dateKey] = new Date(source[dateKey]);
}
});
}
}
processKeys(data);
//hang response off the JSON-serialized data
data.nodeClientResponse = response;
callback.call(client, error, data, response);
}
});
};