-
Notifications
You must be signed in to change notification settings - Fork 22
/
json.ts
48 lines (42 loc) 路 1.21 KB
/
json.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
export function prepareSignBytes(obj: any): any {
if (Array.isArray(obj)) {
return obj.map(prepareSignBytes);
}
// string, number, or null
if (typeof obj !== `object` || obj === null) {
return obj;
}
const sorted: any = {};
Object.keys(obj)
.sort()
.forEach(key => {
if (obj[key] === undefined || obj[key] === null) return;
sorted[key] = prepareSignBytes(obj[key]);
});
return sorted;
}
export abstract class JSONSerializable<A, D, P> {
public abstract toAmino(isClassic?: boolean): A;
public abstract toData(isClassic?: boolean): D;
public abstract toProto(isClassic?: boolean): P;
public toJSON(isClassic?: boolean): string {
return JSON.stringify(prepareSignBytes(this.toData(isClassic)));
}
public toAminoJSON(isClassic?: boolean): string {
return JSON.stringify(prepareSignBytes(this.toAmino(isClassic)));
}
}
export function removeNull(obj: any): any {
if (obj !== null && typeof obj === 'object') {
return Object.entries(obj)
.filter(([, v]) => v != null)
.reduce(
(acc, [k, v]) => ({
...acc,
[k]: v === Object(v) && !Array.isArray(v) ? removeNull(v) : v,
}),
{}
);
}
return obj;
}