-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
201 lines (168 loc) · 5.21 KB
/
index.js
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
'use strict';
var request = require('request');
var pattern = require('urlpattern').express;
var extend = require('extend');
var url = require('url');
var nest = require('./utils').nest;
var isStreamWritable = require('./utils').isStreamWritable;
var Promise = (typeof global.Promise !== 'undefined') ? global.Promise : require('es6-promise').Promise;
function wrapi(baseURL, endpoints, opts) {
var defaultOpts = {
catchHTTP4xx5xx:false
};
opts = opts || defaultOpts;
if (!opts.qs) {
opts.qs = {};
}
endpoints = endpoints || {};
this.toString = function() {
return JSON.stringify({
'baseURL': baseURL,
'endpoints': endpoints,
'opts': opts
});
};
this.register = function(e, endPoint) {
endpoints[e] = endPoint;
return defineEndpoint(e, endPoint);
};
var self = this;
function api(method, apiUrl, qs, epOpts, callback, content) {
// request function for "DELETE" is .del - https://github.com/request/request#requestdel
method = (method == 'DELETE') ? 'DEL' : method;
var apiOpts = extend(true, {}, opts, epOpts);
apiOpts.qs = extend(apiOpts.qs, qs);
if (content) {
apiOpts.body = content;
if (typeof content == 'object' && Object.keys(content).length == 1) {
if (Object.keys(content)[0] == 'formData') {
apiOpts.formData = content['formData']; // https://github.com/request/request#forms
delete apiOpts.body;
apiOpts.json = false;
}
}
}
if (!apiOpts.headers) {
apiOpts.headers = {};
}
if (!apiOpts.headers['User-Agent']) {
apiOpts.headers['User-Agent'] = 'wrapi-client';
}
var req = request[method.toLowerCase()].bind(request, apiUrl, apiOpts);
if (isStreamWritable(callback)) {
return req()
.on('error', function(err) {
callback.emit('error', err);
})
.pipe(callback);
}
return req(function(e, r, body) {
if (e) {
callback(e);
}
else {
// 'PATCH', 'POST', 'PUT' return json as body
if (typeof body == 'string') {
try {
var json = JSON.parse(body);
body = json;
}
catch(e) {
// Not json
}
}
if (apiOpts.catchHTTP4xx5xx && r.statusCode >= 400 && r.statusCode <= 599) {
callback(
{
statusCode: r.statusCode,
body: body
},
null,
r
);
}
else {
callback(null, body, r);
}
}
});
}
//
function defineEndpoint(e, endPoint) {
e = e.split('.');
if (e[0] === 'register') {
throw new RangeError('"register" is a reserved function name for wrapi. Please use an alias (eg. "Register", "_register").');
}
// arguments order - param1, param2, ..., querystring?, body?, callback
function apiEndpoint() {
var callback = [].pop.call(arguments);
// If no callback provided, return a Promise.
if (typeof callback !== 'function' && !isStreamWritable(callback)) {
[].push.call(arguments, callback); // put it back
var args = arguments;
var prom = new Promise(function(resolve, reject) {
callback = function(err, data) {
if (err) {
return reject(err);
}
else {
return resolve(data);
}
};
[].push.call(args, callback);
apiEndpoint.apply(this, args); // recursively call self with callback added
});
return prom;
}
// Last arg is body for 'PATCH', 'POST' & 'PUT'
var body = null;
if (['PATCH', 'POST', 'PUT'].indexOf(endPoint.method) >= 0) {
body = [].pop.call(arguments);
}
// Next is query string
var qs = endPoint.query || {};
if (arguments.length > 0 && !Array.isArray(arguments[arguments.length - 1]) && typeof arguments[arguments.length - 1] === 'object') {
qs = extend(qs, [].pop.call(arguments));
}
// If options overriden for endpoint
var epOpts = endPoint.options || {};
var epBaseUrl = baseURL;
var route = endPoint.path;
// If url overriden for endpoint
if (endPoint.url) {
var urlObj = url.parse(endPoint.url);
route = urlObj.path;
urlObj.pathname = null;
epBaseUrl = url.format(urlObj);
}
var args = arguments;
// If path had place holders, arguments contain values
var placeholders = [];
var regexp = pattern.parse(route, placeholders);
var values = {};
placeholders.forEach(function(ph) {
values[ph.name] = [].shift.call(args);
});
try {
var path = pattern.transform(route, values);
}
catch (exp) {
if (isStreamWritable(callback)) {
throw exp;
}
callback(exp);
return;
}
var apiUrl = url.resolve(epBaseUrl, path);
return api(endPoint.method || 'GET', apiUrl, qs, epOpts, callback, body);
};
nest(self, e, apiEndpoint);
return self;
}
// Create methods for supported endpoints
for (var e in endpoints) {
defineEndpoint(e, endpoints[e]);
}
}
module.exports = wrapi;
module.exports.version = '1.0.1';