-
-
Notifications
You must be signed in to change notification settings - Fork 7.4k
/
streamable-file.ts
68 lines (60 loc) 路 1.66 KB
/
streamable-file.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
import { Readable } from 'stream';
import { types } from 'util';
import { isFunction } from '../utils/shared.utils';
import { StreamableFileOptions } from './streamable-options.interface';
export interface StreamableHandlerResponse {
statusCode: number;
send: (msg: string) => void;
}
export class StreamableFile {
private readonly stream: Readable;
protected handleError: (
err: Error,
response: StreamableHandlerResponse,
) => void = (err: Error, res) => {
res.statusCode = 400;
res.send(err.message);
};
constructor(buffer: Uint8Array, options?: StreamableFileOptions);
constructor(readable: Readable, options?: StreamableFileOptions);
constructor(
bufferOrReadStream: Uint8Array | Readable,
readonly options: StreamableFileOptions = {},
) {
if (types.isUint8Array(bufferOrReadStream)) {
this.stream = new Readable();
this.stream.push(bufferOrReadStream);
this.stream.push(null);
this.options.length ??= bufferOrReadStream.length;
} else if (bufferOrReadStream.pipe && isFunction(bufferOrReadStream.pipe)) {
this.stream = bufferOrReadStream;
}
}
getStream(): Readable {
return this.stream;
}
getHeaders() {
const {
type = 'application/octet-stream',
disposition = undefined,
length = undefined,
} = this.options;
return {
type,
disposition,
length,
};
}
get errorHandler(): (
err: Error,
response: StreamableHandlerResponse,
) => void {
return this.handleError;
}
setErrorHandler(
handler: (err: Error, response: StreamableHandlerResponse) => void,
) {
this.handleError = handler;
return this;
}
}