-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathreader.ts
62 lines (54 loc) · 1.75 KB
/
reader.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
import { Readable } from "stream";
import { DataSourceReaderNotOpenedError } from "../errors";
/**
* An interface for reading data to import into Firestore from a stream.
*/
export interface IDataSourceReader {
/**
* The path to where data will be read from.
*/
readonly path: string;
/**
* Open a connection to the read stream.
*/
open?(): Promise<void>;
/**
* Read lines of data from the stream.
*
* Returns a list of promises, where each promise corresponds
* to an asynchronous invocation of the {@link onData} callback.
* If {@link onData} is not asynchronous, it will not be returned.
*/
read(
onData: (data: string) => void | Promise<void>,
): Promise<Promise<void>[]>;
}
/**
* An abstract implementation of {@link IDataSourceReader} using {@link Readable}.
*
* You can extend this class to create your own implementation of a data
* source that reads from a {@link Readable} stream.
*/
export abstract class StreamReader implements IDataSourceReader {
protected abstract stream?: Readable;
abstract readonly path: string;
abstract open(): Promise<void>;
async read(
onData: (data: string) => void | Promise<void>,
): Promise<Promise<void>[]> {
const promises: Promise<void>[] = [];
return new Promise((resolve, reject) => {
if (!this.stream) return reject(new DataSourceReaderNotOpenedError());
this.stream
.on("error", (error) => reject(error))
.on("readable", async () => {
const buffer: Buffer | null = this.stream!.read();
const data = buffer?.toString();
if (!data) return;
const promise = onData(data);
if (promise) promises.push(promise);
})
.on("end", () => resolve(promises));
});
}
}