-
Notifications
You must be signed in to change notification settings - Fork 1
/
bson-value.ts
58 lines (48 loc) · 1.43 KB
/
bson-value.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
/**
* @module kryo/writers/bson-value
*/
import bson from "bson";
import { Writer } from "../core";
import { JsonWriter } from "./json";
import { StructuredWriter } from "./structured";
export class BsonValueWriter extends StructuredWriter {
private readonly bsonLib: typeof bson;
constructor(bsonLib: typeof bson) {
super();
this.bsonLib = bsonLib;
}
writeFloat64(value: number): number {
return value;
}
writeBoolean(value: boolean): boolean {
return value;
}
writeNull(): null {
return null;
}
writeBytes(value: Uint8Array): bson.Binary {
// TODO: Update Node type definitions
return new this.bsonLib.Binary(Buffer.from(value as any));
}
writeDate(value: Date): Date {
return new Date(value.getTime());
}
writeString(value: string): string {
return value;
}
writeMap(
size: number,
keyHandler: <KW>(index: number, mapKeyWriter: Writer<KW>) => KW,
valueHandler: <VW>(index: number, mapValueWriter: Writer<VW>) => VW,
): any {
const result: any = {};
for (let index: number = 0; index < size; index++) {
// TODO: Use a specialized writer that only accepts strings and numbers (KeyMustBeAStringError)
// Let users build custom serializers if they want
const jsonWriter: JsonWriter = new JsonWriter();
const key: any = keyHandler(index, jsonWriter);
result[JSON.stringify(key)] = valueHandler(index, this);
}
return result;
}
}