Core

/client/src/parse.ts (2.3 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
export const Parse = {
date: (x: unknown, dflt?: () => Date): Date => {
const d = Parse.dateOpt(x);
if (d !== undefined) {
return d;
}
if (dflt === undefined) {
throw new Error(`invalid date input [${x}] of type [${typeof x}]`);
}
return dflt();
},

dateOpt: (x: unknown): Date | undefined => {
if (x instanceof Date) {
return x;
}
if (typeof x === "string") {
return new Date(x);
}
return undefined;
},

float: (x: unknown, dflt?: () => number): number => {
const s = Parse.floatOpt(x);
if (s !== undefined) {
return s;
}
if (dflt === undefined) {
throw new Error(`invalid float input [${x}] of type [${typeof x}]`);
}
return dflt();
},

floatOpt: (x: unknown): number | undefined => {
if (typeof x === "number") {
return x;
}
if (typeof x === "string") {
return parseFloat(x);
}
return undefined;
},

int: (x: unknown, dflt?: () => number): number => {
const s = Parse.intOpt(x);
if (s !== undefined) {
return s;
}
if (dflt === undefined) {
throw new Error(`invalid integer input [${x}] of type [${typeof x}]`);
}
return dflt();
},

intOpt: (x: unknown): number | undefined => {
if (typeof x === "number") {
return x;
}
if (typeof x === "string") {
return parseInt(x, 10);
}
return undefined;
},

obj: (x: unknown, dflt?: () => { [key: string]: unknown }): { [key: string]: unknown } => {
const o = Parse.objOpt(x);
if (o !== undefined) {
return o;
}
if (dflt === undefined) {
throw new Error(`invalid object input [${x}] of type [${typeof x}]`);
}
return dflt();
},

objOpt: (x: unknown): { [key: string]: unknown } | undefined => {
if (typeof x === "object" && x !== null) {
return x as { [key: string]: unknown };
}
return undefined;
},

string: (x: unknown, dflt?: () => string): string => {
const s = Parse.stringOpt(x);
if (s !== undefined) {
return s;
}
if (dflt === undefined) {
throw new Error(`invalid string input [${x}] of type [${typeof x}]`);
}
return dflt();
},

stringOpt: (x: unknown): string | undefined => {
if (typeof x === "string") {
return x;
}
return undefined;
}
};