forked from sindresorhus/got
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcacheable-request-stub.js
57 lines (46 loc) · 1.23 KB
/
cacheable-request-stub.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
'use strict';
const EventEmitter = require('events');
class CacheableRequest {
constructor(request, cacheAdapter) {
if (typeof request !== 'function') {
throw new TypeError('Parameter `request` must be a function');
}
return this.createCacheableRequest(request);
}
createCacheableRequest(request) {
return (opts, cb) => {
const ee = new EventEmitter();
const makeRequest = opts => {
const handler = response => {
ee.emit('response', response);
if (typeof cb === 'function') {
cb(response);
}
};
try {
const req = request(opts, handler);
ee.emit('request', req);
} catch (err) {
ee.emit('error', new CacheableRequest.RequestError(err));
}
};
process.nextTick(() => makeRequest(opts))
return ee;
};
}
}
CacheableRequest.RequestError = class extends Error {
constructor(err) {
super(err.message);
this.name = 'RequestError';
Object.assign(this, err);
}
};
CacheableRequest.CacheError = class extends Error {
constructor(err) {
super(err.message);
this.name = 'CacheError';
Object.assign(this, err);
}
};
module.exports = CacheableRequest;