-
Notifications
You must be signed in to change notification settings - Fork 14
/
streamableAxios.js
57 lines (50 loc) · 1.21 KB
/
streamableAxios.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
const stream = require("stream");
const util = require("util");
const axios = require("axios");
function AxiosStream(options) {
const self = this;
self.options = options;
stream.Stream.call(self);
self.init();
}
util.inherits(AxiosStream, stream.Stream);
AxiosStream.prototype.init = function () {
const self = this;
if (self._started) {
self.emit("error", new Error("Already started."));
}
self.on("pipe", (src) => {
delete src.headers["host"];
self.options = {
headers: src.headers,
method: src.method,
...self.options,
};
});
};
AxiosStream.prototype.start = function () {
const self = this;
self._started = true;
};
AxiosStream.prototype.end = function () {
const self = this;
if (!self._started) {
self.start();
}
if (self._started) {
axios({ ...self.options, responseType: "stream" })
.then((stream) => {
stream.data.on("data", (chunk) => {
self.emit("data", chunk);
});
stream.data.on("end", () => {
self.emit("end");
});
})
.catch((e) => {
self.emit("error", e);
});
}
};
const streamableAxios = (options) => new AxiosStream(options);
module.exports = streamableAxios;