-
-
Notifications
You must be signed in to change notification settings - Fork 7.4k
/
streamable-file.ts
92 lines (81 loc) 路 2.18 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { Readable } from 'stream';
import { types } from 'util';
import { HttpStatus } from '../enums';
import { isFunction } from '../utils/shared.utils';
import { StreamableFileOptions, StreamableHandlerResponse } from './interfaces';
import { Logger } from '../services';
/**
* @see [Streaming files](https://docs.nestjs.com/techniques/streaming-files)
*
* @publicApi
*/
export class StreamableFile {
private readonly stream: Readable;
protected logger = new Logger('StreamableFile');
protected handleError: (
err: Error,
response: StreamableHandlerResponse,
) => void = (err: Error, res) => {
if (res.destroyed) {
return;
}
if (res.headersSent) {
res.end();
return;
}
res.statusCode = HttpStatus.BAD_REQUEST;
res.send(err.message);
};
protected logError: (err: Error) => void = (err: Error) => {
this.logger.error(err.message, err.stack);
};
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;
}
get errorLogger() {
return this.logError;
}
setErrorLogger(handler: (err: Error) => void) {
this.logError = handler;
return this;
}
}