-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
79 lines (74 loc) · 1.86 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
const http = require("http");
const concat = require("concat-stream");
const request = function(app) {
let server;
const headers = {};
let path;
let method;
let postData;
const obj = {};
const buildOptions = function(method, port, path) {
const options = { port, path, method, headers };
return options;
};
const pendingPort = new Promise((resolve, reject) => {
server = http.createServer(app).listen(0, e => {
if (e) {
return reject(e);
} else {
return resolve(server.address().port);
}
});
});
obj.then = function(resolve, reject) {
var x = new Promise((innerResolve, innerReject) => {
var close = function(e, _reject) {
if (server) {
server.close(() => {
_reject(e);
})
} else {
_reject(e)
}
}
pendingPort
.then(port => {
const req = http.request(buildOptions(method, port, path), res => {
res.pipe(
concat(body => {
res.text = body.toString();
server.close(() => {
innerResolve(res);
})
})
);
});
if (method == "POST") {
req.setHeader("Content-Type", "application/json");
req.write(JSON.stringify(postData));
}
req.on("error",(e) => close(e,innerReject));
req.end();
})
.catch((e) => close(e,innerReject));
});
return x.then(resolve, reject);
};
obj.set = function(key, value) {
headers[key] = value;
return obj;
};
obj.get = function(_path) {
method = "GET";
path = _path;
return obj;
};
obj.post = function(_path, _postData) {
method = "POST";
path = _path;
postData = _postData;
return obj;
};
return obj;
};
module.exports = exports = request;