http.js
3.25 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const axios_1 = require("axios");
const stream_1 = require("stream");
const exceptions_1 = require("./exceptions");
const fileType = require("file-type");
const qs = require("querystring");
const pkg = require("../package.json");
class HTTPClient {
constructor(config = {}) {
this.config = config;
const { baseURL, defaultHeaders } = config;
this.instance = axios_1.default.create({
baseURL,
headers: Object.assign({}, defaultHeaders, {
"User-Agent": `${pkg.name}/${pkg.version}`,
}),
});
this.instance.interceptors.response.use(res => res, err => Promise.reject(this.wrapError(err)));
}
async get(url, params) {
const res = await this.instance.get(url, { params });
return res.data;
}
async getStream(url, params) {
const res = await this.instance.get(url, {
params,
responseType: "stream",
});
return res.data;
}
async post(url, body) {
const res = await this.instance.post(url, body, {
headers: { "Content-Type": "application/json" },
});
const { responseParser } = this.config;
if (responseParser)
return responseParser(res);
else
return res.data;
}
async postForm(url, body) {
const res = await this.instance.post(url, qs.stringify(body), {
headers: { "Content-Type": "application/x-www-form-urlencoded" },
});
return res.data;
}
async postBinary(url, data, contentType) {
const buffer = await (async () => {
if (Buffer.isBuffer(data)) {
return data;
}
else if (data instanceof stream_1.Readable) {
return new Promise((resolve, reject) => {
const buffers = [];
let size = 0;
data.on("data", (chunk) => {
buffers.push(chunk);
size += chunk.length;
});
data.on("end", () => resolve(Buffer.concat(buffers, size)));
data.on("error", reject);
});
}
else {
throw new Error("invalid data type for postBinary");
}
})();
const res = await this.instance.post(url, buffer, {
headers: {
"Content-Type": contentType || fileType(buffer).mime,
"Content-Length": buffer.length,
},
});
return res.data;
}
async delete(url, params) {
const res = await this.instance.delete(url, { params });
return res.data;
}
wrapError(err) {
if (err.response) {
return new exceptions_1.HTTPError(err.message, err.response.status, err.response.statusText, err);
}
else if (err.code) {
return new exceptions_1.RequestError(err.message, err.code, err);
}
else if (err.config) {
// unknown, but from axios
return new exceptions_1.ReadError(err);
}
// otherwise, just rethrow
return err;
}
}
exports.default = HTTPClient;