-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrstream.ts
53 lines (51 loc) · 1.07 KB
/
rstream.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
const transformContent = {
inString: false,
objectDepth: 0,
buffer: "",
start() {}, // required.
transform(
chunk: string | null,
controller: TransformStreamDefaultController,
) {
if (chunk === null) {
controller.terminate();
return;
}
for (const c of chunk) {
if (this.inString) {
// TODO: handle escaped quotes
if (c === '"') this.inString = false;
this.buffer += c;
continue;
}
let done = false;
switch (c) {
case "{":
this.objectDepth++;
break;
case "}":
this.objectDepth--;
if (this.objectDepth === 0) done = true;
break;
default:
break;
}
this.buffer += c;
if (done) {
// TODO: error handling
controller.enqueue(JSON.parse(this.buffer));
this.buffer = "";
}
}
},
flush() {
/* do any destructor work here */
},
};
export class SplitJsonObjectsStream extends TransformStream {
constructor() {
super({
...transformContent,
});
}
}