-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
430 lines (352 loc) · 8.57 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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
const { doRequest } = require ('httpreq');
const { promisify } = require ('es6-promisify');
// Default config
const defaults = {
email: null,
apikey: null,
timeout: 5000,
};
let pkg = {
test: {
get: null,
},
locations: {},
browsers: {},
account: {},
};
let config = {};
/**
* Get info about resource type
*
* @param {string} name The resource name
* @return {object} Resource info object
*/
function resourceType (name) {
let info = {
binary: false,
path: name.replace ('_', '-'),
};
if (info.path.match (/^(filmstrip|pagespeed-files|report-pdf(-full)?|screenshot|video)$/)) {
info.binary = true;
}
if (info.path === 'report-pdf-full') {
info.path = 'report-pdf?full=1';
}
return info;
}
/**
* Make an error
*
* @return {Error}
*
* @param {string} msg Error.message
* @param {mixed} err Error.error
* @param {number|null} code Error.statusCode
* @param {string|null} type Error.contentType
*/
function doError (msg, err, code, type) {
let error = new Error (msg);
error.error = err;
error.statusCode = code;
error.contentType = type;
return error;
}
/**
* Process API response
*
* @callback callback
* @return {void}
*
* @param {object} options httpreq options
* @param {Error|null} err httpreq Error
* @param {object} res httpreq response
* @param {function} callback `(err, data)`
*/
function apiResponse (options, err, res, callback) {
let type;
let size;
let code;
let data;
let error = null;
if (err) {
error = doError ('request failed', err, null, null);
callback (error);
return;
}
type = String (res.headers ['content-type']) .split (';') [0];
size = String (res.headers ['content-length']);
code = res.statusCode;
data = res.body;
// Received data, expecting binary
if (size && options.binary && type.match (/\/(pdf|jpeg|tar)$/)) {
callback (null, data);
return;
}
// Received something else
try {
data = JSON.parse (data);
if (data.error) {
error = doError ('API error', data.error, code, type);
callback (error);
return;
}
}
catch (e) {
error = doError ('invalid response', e, code, type);
callback (error);
return;
}
// It's real data
callback (null, data);
}
/**
* Send API request
*
* @callback callback
* @return {void}
*
* @param {object} props
* @param {boolean} [props.binary=false] Expect binary response
* @param {string} props.method HTTP method
* @param {object} [props.params] Method parameters
* @param {string} props.path Method path
* @param {function} callback `(err, data)`
*/
function apiRequest (props, callback) {
const options = {
url: 'https://gtmetrix.com/api/0.1/' + props.path,
parameters: props.params || null,
method: props.method,
headers: {
'User-Agent': 'gtmetrix.js (https://www.npmjs.com/package/gtmetrix)',
},
timeout: parseInt (config.timeout, 10) || defaults.timeout,
auth: config.email + ':' + config.apikey,
binary: props.binary || false,
};
doRequest (options, (err, res) => {
apiResponse (options, err, res, callback);
});
}
/**
* Create test
*
* @callback callback
* @return {Promise<object>}
*
* @param {object} params
* @param {function} [callback] `(err, data)`
*/
pkg.test.create = promisify ((params, callback) => {
const props = {
method: 'POST',
path: 'test',
params: params,
};
apiRequest (props, callback);
});
/**
* Process callback when polling
*
* @callback callback
* @return {boolean} Stop polling? true = yes
*
* @param {object} props Request properties
* @param {Error|null} err Response error
* @param {object} data Response data
* @param {function} callback `(err, data)`
*/
function pollingCallback (props, err, data, callback) {
// API error saying we need to wait
if (err && String (err.error).match (/Data not yet available/)) {
return false;
}
// Another API error
if (err) {
callback (err);
return true;
}
// No API error, binary expected = ok complete
if (props.binary) {
callback (null, data);
return true;
}
// No error, non-binary, not running = ok complete
if (!String (data.state).match (/^(started|queued)$/)) {
callback (null, data);
return true;
}
// else keep polling
return false;
}
/**
* Process test response
*
* @callback callback
* @return {void}
*
* @param {object} params
* @param {bool} params.polling Keep polling for updates
* @param {string} params.testId Test ID
* @param {string} params.resource Test resource
* @param {object} params.props Request params
* @param {Error|null} err Response error
* @param {mixed} data Response data
* @param {function} callback `(err, data)`
*/
function testResponse (params, err, data, callback) {
let retryInterval;
let complete;
if (err && !params.polling) {
callback (err);
return;
}
if (!params.polling) {
callback (null, data);
return;
}
if (params.polling === true) {
params.polling = 5000;
}
if (typeof params.polling === 'number') {
complete = pollingCallback (params.props, err, data, callback);
if (complete) {
return;
}
// Test is still running
retryInterval = setInterval (() => {
pkg.test.get (params.testId, params.resource, (pErr, pData) => {
const pComplete = pollingCallback (params.props, pErr, pData, callback);
if (pComplete) {
clearInterval (retryInterval);
}
});
}, params.polling);
}
}
/**
* Get test result
*
* @callback callback
* @return {Promise<object>}
*
* @param {string} testId Test ID
* @param {string} [resource] Resource to get, i.e. `screenshot`
* @param {number} [polling] Poll state until completion, in ms
* @param {function} [callback] `(err, data)`
*/
pkg.test.get = promisify ((testId, resource, polling, callback) => {
let resourceInfo = {};
let params = {
testId,
resource,
polling,
props: {
method: 'GET',
path: 'test/' + testId,
},
};
if (typeof polling === 'function') {
callback = polling;
params.polling = null;
}
switch (typeof resource) {
case 'function':
callback = resource;
params.resource = null;
params.polling = null;
break;
case 'number':
params.polling = resource;
params.resource = null;
break;
case 'string':
resourceInfo = resourceType (resource);
params.props.path += '/' + resourceInfo.path;
params.props.binary = resourceInfo.binary;
break;
default:
break;
}
apiRequest (params.props, (err, data) => {
testResponse (params, err, data, callback);
});
});
/**
* List locations
*
* @callback callback
* @return {Promise<object>}
*
* @param {function} [callback] `(err, data)`
*/
pkg.locations.list = promisify ((callback) => {
const props = {
method: 'GET',
path: 'locations',
};
apiRequest (props, callback);
});
/**
* List browsers
*
* @callback callback
* @return {Promise<object>}
*
* @param {function} [callback] `(err, data)`
*/
pkg.browsers.list = promisify ((callback) => {
const props = {
method: 'GET',
path: 'browsers',
};
apiRequest (props, callback);
});
/**
* Get browser
*
* @callback callback
* @return {Promise<object>}
*
* @param {string} browserId
* @param {function} [callback] `(err, data)`
*/
pkg.browsers.get = promisify ((browserId, callback) => {
const props = {
method: 'GET',
path: 'browsers/' + browserId,
};
apiRequest (props, callback);
});
/**
* Get account status
*
* @callback callback
* @return {Promise<object>}
*
* @param {function} [callback] `(err, data)`
*/
pkg.account.status = promisify ((callback) => {
const props = {
method: 'GET',
path: 'status',
};
apiRequest (props, callback);
});
/**
* Module interface
*
* @return {object} Methods
*
* @param {object} props
* @param {string} props.email API email
* @param {string} props.apikey API key
* @param {number} [props.timeout=5000] Request timeut in ms
*/
module.exports = (props) => {
let key;
for (key in props) {
config [key] = props [key];
}
return pkg;
};