-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathstreamInput.ts
More file actions
68 lines (61 loc) · 1.94 KB
/
streamInput.ts
File metadata and controls
68 lines (61 loc) · 1.94 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
import { Readable } from "stream";
import { LocalInputSource } from "./localInputSource.js";
import { INPUT_TYPE_STREAM } from "./inputSource.js";
import { logger } from "@/logger.js";
import { MindeeInputSourceError } from "@/errors/index.js";
interface StreamInputProps {
inputStream: Readable;
filename: string;
}
export class StreamInput extends LocalInputSource {
private readonly inputStream: Readable;
fileObject: Buffer = Buffer.alloc(0);
constructor({ inputStream, filename }: StreamInputProps) {
super({
inputType: INPUT_TYPE_STREAM,
});
this.filename = filename;
this.inputStream = inputStream;
}
async init() {
if (this.initialized) {
return;
}
logger.debug("Loading from stream");
this.fileObject = await this.stream2buffer(this.inputStream);
this.mimeType = await this.checkMimetype();
this.initialized = true;
}
async stream2buffer(stream: Readable, signal?: AbortSignal): Promise<Buffer> {
return new Promise<Buffer>((resolve, reject) => {
if (stream.closed || stream.destroyed) {
return reject(new MindeeInputSourceError("Stream is already closed"));
}
if (signal?.aborted) {
return reject(new MindeeInputSourceError("Operation aborted"));
}
const onAbort = () => {
stream.destroy();
reject(new MindeeInputSourceError("Operation aborted"));
};
if (signal) {
signal.addEventListener("abort", onAbort, { once: true });
}
const cleanup = () => {
signal?.removeEventListener("abort", onAbort);
};
const _buf: Buffer[] = [];
stream.pause();
stream.on("data", (chunk) => _buf.push(chunk));
stream.on("end", () => {
cleanup();
resolve(Buffer.concat(_buf));
});
stream.on("error", (err) => {
cleanup();
reject(new MindeeInputSourceError(`Error converting stream - ${err}`));
});
stream.resume();
});
}
}