-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
72 lines (63 loc) · 1.61 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
const http = require('http');
const https = require('https');
const assert = require('assert');
const Stream = require('stream');
const { buildForm } = require('./form');
const request = (method, url, payload, headers) => {
const client = url.startsWith('https://') ? https : http;
return new Promise((resolve, reject) => {
const req = client.request(url, {
method,
headers,
}, resolve);
req.once('error', reject);
if (payload instanceof Stream) {
payload.pipe(req);
} else {
req.end(payload);
}
});
};
const readStream = stream => {
const buffer = [];
return new Promise((resolve, reject) => {
stream
.on('error', reject)
.on('data', chunk => buffer.push(chunk))
.on('end', () => resolve(Buffer.concat(buffer)))
});
};
const ensureStatusCode = expected => {
if (!Array.isArray(expected))
expected = [expected];
return res => {
const { statusCode } = res;
assert.ok(expected.includes(statusCode), `status code must be "${expected}" but actually "${statusCode}"`);
return res;
};
};
const get = (url, headers) =>
request('get', url, '', headers);
const post = (url, payload, headers) =>
request('post', url, payload, headers);
const getJSON = (url, headers) =>
Promise
.resolve()
.then(() => get(url, headers))
.then(readStream)
.then(JSON.parse);
const postJSON = (url, payload, headers) =>
Promise
.resolve()
.then(() => post(url, JSON.stringify(payload), headers))
.then(readStream)
module.exports = {
request,
get,
post,
readStream,
ensureStatusCode,
getJSON,
postJSON,
buildForm,
};