-
Notifications
You must be signed in to change notification settings - Fork 8
/
Generate.gs
90 lines (78 loc) · 2.74 KB
/
Generate.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
/**
Every REST client call (get, put, post, delete[, create, update]) shares this common signature.
This function returns an object which groks this signature from an arguments array:
get({
Some:'parameter'
}, function(err, data, response) {
console.log(err); //The error object from "request" module
console.log(data); //The JSON-parsed response from Twilio
console.log(response); //The node http.ClientResponse object from "request"
});
- or -
get({
Some:'parameter'
});
- or -
get(function(err, data) {
});
*/
function process_(args) {
var params = (typeof args[0] !== 'function') ? args[0] : {},
twilioParams = {},
callback = (typeof args[0] === 'function') ? args[0] : args[1];
//"Twilify" any request parameters
for (var key in params) {
if (params.hasOwnProperty(key)) {
//assume first letter in variable name needs uppercasing, otherwise assume fine
var twilioKey = key.charAt(0).toUpperCase() + key.slice(1);
twilioParams[twilioKey] = params[key];
}
}
return {
twilioParams:twilioParams,
callback:callback
};
}
//Generate a Twilio HTTP client call
var generate_ = function (client, method, url) {
return function () {
var args = process_(arguments),
requestArgs = {
url:url,
method:method
};
//Send parameters, if supplied
if (args.twilioParams && method === 'GET') {
requestArgs.qs = args.twilioParams;
} else if (args.twilioParams) {
requestArgs.form = args.twilioParams;
}
//make request
client.request(requestArgs, args.callback);
};
};
//generate several rest functions on a given object
generate_.restFunctions = function (object, client, methods, resource) {
for (var i = 0, l = methods.length; i < l; i++) {
var method = methods[i];
//can be either a string indicating an HTTP method to generate,
//or an object mapping a function name to an HTTP verb
if (typeof method === 'string') {
if (method === 'GET') {
object.get = object.list = generate_(client, method, resource);
} else if (method === 'POST') {
object.post = generate_(client, method, resource);
} else if (method === 'PUT') {
object.put = generate_(client, method, resource);
} else if (method === 'DELETE') {
object['delete'] = generate_(client, method, resource);
}
}
else {
//Create an alias for the given method name to a REST function
for (var key in method) {
object[key] = object[method[key].toLowerCase()];
}
}
}
};