-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
76 lines (57 loc) · 1.48 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
const http = require('http');
const fetch = require('node-fetch');
const { map, forEach, assign } = require('lodash');
const methods = map(http.METHODS, m => m.toLowerCase());
class Testtp {
constructor(server) {
this._server = server;
this.port = this._server.address().port;
this.address = this._server.address().address;
this.protocol = 'http://';
this.url = [[ this.protocol, this.address].join(''), this.port ].join(':');
forEach(methods, m => {
this[m] = (path, opt) => {
opt = assign({}, opt, { method: m });
path = [ this.url, path ].join('');
return fetch(path, opt);
};
});
}
}
function tryClose(server, res, rej) {
try {
server.close(res);
} catch(e) {
rej ? rej(e) : res(e);
}
}
Testtp.prototype.close = function(cb) {
if(typeof cb === 'function') {
tryClose(this._server, cb);
return;
}
return new Promise((res, rej) => {
tryClose(this._server, res, rej);
});
};
function tryListen(server, res, rej) {
try {
server.listen(0, '127.0.0.1', () =>
rej ? res(new Testtp(server)) : res(null, new Testtp(server)));
} catch(e) {
rej ? rej(e) : res(e);
}
}
module.exports = (server, cb) => {
// if an express or koa object is passed
if(!(server instanceof http.Server)) {
server = http.createServer(server);
}
if(typeof cb === 'function') {
tryListen(server, cb);
return;
}
return new Promise((res, rej) => {
tryListen(server, res, rej);
});
};