forked from glideapps/quicktype
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompressedJSONFromStream.ts
More file actions
67 lines (60 loc) · 2.07 KB
/
Copy pathCompressedJSONFromStream.ts
File metadata and controls
67 lines (60 loc) · 2.07 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
import { Readable } from "readable-stream";
import { CompressedJSON, Value } from "quicktype-core";
import { Parser } from "stream-json";
const methodMap: { [name: string]: string } = {
startObject: "pushObjectContext",
endObject: "finishObject",
startArray: "pushArrayContext",
endArray: "finishArray",
startNumber: "handleStartNumber",
numberChunk: "handleNumberChunk",
endNumber: "handleEndNumber",
keyValue: "setPropertyKey",
stringValue: "commitString",
nullValue: "commitNull",
trueValue: "handleTrueValue",
falseValue: "handleFalseValue"
};
export class CompressedJSONFromStream extends CompressedJSON<Readable> {
async parse(readStream: Readable): Promise<Value> {
const combo = new Parser({ packKeys: true, packStrings: true });
combo.on("data", (item: { name: string; value: string | undefined }) => {
if (typeof methodMap[item.name] === "string") {
(this as any)[methodMap[item.name]](item.value);
}
});
const promise = new Promise<Value>((resolve, reject) => {
combo.on("end", () => {
resolve(this.finish());
});
combo.on("error", (err: any) => {
reject(err);
});
});
readStream.setEncoding("utf8");
readStream.pipe(combo);
readStream.resume();
return promise;
}
protected handleStartNumber = (): void => {
this.pushContext();
this.context.currentNumberIsDouble = false;
};
protected handleNumberChunk = (s: string): void => {
const ctx = this.context;
if (!ctx.currentNumberIsDouble && /[\.e]/i.test(s)) {
ctx.currentNumberIsDouble = true;
}
};
protected handleEndNumber(): void {
const isDouble = this.context.currentNumberIsDouble;
this.popContext();
this.commitNumber(isDouble);
}
protected handleTrueValue(): void {
this.commitBoolean(true);
}
protected handleFalseValue(): void {
this.commitBoolean(false);
}
}