-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstreamObjectTransformer.mjs
60 lines (57 loc) · 1.59 KB
/
streamObjectTransformer.mjs
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
import Stream from "node:stream";
import StreamJSON from "stream-json";
const updatePath = (path) => {
const lastPathValue = path[path.length - 1];
if (typeof lastPathValue === "number") {
return [...path.slice(0, -1), lastPathValue + 1];
}
return path;
};
const streamObjectTransformer = () =>
Stream.compose(
StreamJSON.parser({
streamKeys: false,
streamValues: false,
}),
async function* (source) {
let path = [];
for await (const chunk of source) {
const lastPathValue = path[path.length - 1];
switch (chunk.name) {
case "startArray":
path = [...path, 0];
break;
case "endArray":
path = path.slice(0, -1);
if (lastPathValue === 0) {
yield { key: path, value: [] };
}
path = updatePath(path);
break;
case "startObject":
path = [...path, null];
break;
case "endObject":
path = path.slice(0, -1);
if (lastPathValue === null) {
yield { key: path, value: {} };
}
path = updatePath(path);
break;
case "keyValue":
path = [...path.slice(0, -1), chunk.value];
break;
default:
yield {
key: path,
value:
chunk.name === "numberValue"
? parseFloat(chunk.value)
: chunk.value,
};
path = updatePath(path);
}
}
}
);
export default streamObjectTransformer;