forked from sindresorhus/got
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathas-stream.ts
147 lines (119 loc) · 3.78 KB
/
as-stream.ts
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import duplexer3 = require('duplexer3');
import stream = require('stream');
import {IncomingMessage, ServerResponse} from 'http';
import {Duplex as DuplexStream, PassThrough as PassThroughStream} from 'stream';
import {HTTPError, ReadError} from './errors';
import requestAsEventEmitter, {proxyEvents} from './request-as-event-emitter';
import {GeneralError, GotEvents, NormalizedOptions, Response} from './types';
export class ProxyStream<T = unknown> extends DuplexStream implements GotEvents<ProxyStream<T>> {
isFromCache?: boolean;
}
export default function asStream<T>(options: NormalizedOptions): ProxyStream<T> {
const input = new PassThroughStream();
const output = new PassThroughStream();
const proxy = duplexer3(input, output) as ProxyStream;
const piped = new Set<ServerResponse>();
let isFinished = false;
options.retry.calculateDelay = () => 0;
if (options.body || options.json || options.form) {
proxy.write = () => {
proxy.destroy();
throw new Error('Got\'s stream is not writable when the `body`, `json` or `form` option is used');
};
} else if (options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH') {
options.body = input;
} else {
proxy.write = () => {
proxy.destroy();
throw new TypeError(`The \`${options.method}\` method cannot be used with a body`);
};
}
const emitter = requestAsEventEmitter(options);
const emitError = async (error: GeneralError): Promise<void> => {
try {
for (const hook of options.hooks.beforeError) {
// eslint-disable-next-line no-await-in-loop
error = await hook(error);
}
proxy.emit('error', error);
} catch (error_) {
proxy.emit('error', error_);
}
};
// Cancels the request
proxy._destroy = (error, callback) => {
callback(error);
emitter.abort();
};
emitter.on('response', (response: Response) => {
const {statusCode, isFromCache} = response;
proxy.isFromCache = isFromCache;
if (options.throwHttpErrors && statusCode !== 304 && (statusCode < 200 || statusCode > 299)) {
emitError(new HTTPError(response, options));
return;
}
{
const read = proxy._read;
proxy._read = (...args) => {
isFinished = true;
proxy._read = read;
return read.apply(proxy, args);
};
}
if (options.encoding) {
proxy.setEncoding(options.encoding);
}
stream.pipeline(
response,
output,
error => {
if (error && error.message !== 'Premature close') {
emitError(new ReadError(error, options));
}
}
);
for (const destination of piped) {
if (destination.headersSent) {
continue;
}
for (const [key, value] of Object.entries(response.headers)) {
// Got gives *decompressed* data. Overriding `content-encoding` header would result in an error.
// It's not possible to decompress already decompressed data, is it?
const isAllowed = options.decompress ? key !== 'content-encoding' : true;
if (isAllowed) {
destination.setHeader(key, value!);
}
}
destination.statusCode = response.statusCode;
}
proxy.emit('response', response);
});
proxyEvents(proxy, emitter);
emitter.on('error', (error: GeneralError) => proxy.emit('error', error));
const pipe = proxy.pipe.bind(proxy);
const unpipe = proxy.unpipe.bind(proxy);
proxy.pipe = (destination, options) => {
if (isFinished) {
throw new Error('Failed to pipe. The response has been emitted already.');
}
pipe(destination, options);
if (destination instanceof ServerResponse) {
piped.add(destination);
}
return destination;
};
proxy.unpipe = stream => {
piped.delete(stream as ServerResponse);
return unpipe(stream);
};
proxy.on('pipe', source => {
if (source instanceof IncomingMessage) {
options.headers = {
...source.headers,
...options.headers
};
}
});
proxy.isFromCache = undefined;
return proxy;
}