-
Notifications
You must be signed in to change notification settings - Fork 257
/
request.js
72 lines (57 loc) · 1.47 KB
/
request.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
'use strict';
const https = require('https');
const post = (url, data, cb) => {
if (!url) {
cb(new Error('request.post(url, data, cb): url must be non-empty.'));
return;
}
if (typeof url !== 'string') {
cb(new Error('request.post(url, data, cb): url must be a String.'));
return;
}
if (!data) {
cb(new Error('request.post(url, data, cb): data must be non-empty.'));
return;
}
if (typeof data !== 'string') {
cb(new Error('request.post(url, data, cb): data must be a String.'));
return;
}
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data),
},
};
let errored = false;
const req = https.request(url, options, (res) => {
res.setEncoding('utf8');
const { statusCode } = res;
const body = [];
res.on('data', chunk => {
// Buffer.concat below will complain if the chunks are strings.
// this should only ever happen in the nock https mock,
// but let's make sure.
if (typeof chunk === 'string') {
chunk = Buffer.from(chunk);
}
body.push(chunk);
});
res.on('end', () => {
if (!errored) {
cb(null, { statusCode }, Buffer.concat(body).toString());
}
});
});
req.on('error', (e) => {
errored = true;
cb(e);
});
// Write data to request body
req.write(`json=${encodeURIComponent(data)}`);
req.end();
};
module.exports = {
post,
};