-
Notifications
You must be signed in to change notification settings - Fork 0
/
safe_unknown.ts
269 lines (205 loc) · 8.26 KB
/
safe_unknown.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
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import { BadParamsError } from './errors.ts'
export type SafeUnknownType = 'null' | 'string' | 'number' | 'bigint' | 'boolean' | 'bytes' | 'array' | 'object' | 'function'
export class SafeUnknown {
data: unknown
#contextPath: string
constructor(data: unknown, contextPath = '$') {
this.data = data
this.#contextPath = contextPath
}
getType(): SafeUnknownType {
if (this.data === null) return 'null'
if (typeof this.data === 'string') return 'string'
if (typeof this.data === 'number') return 'number'
if (typeof this.data === 'bigint') return 'bigint'
if (typeof this.data === 'boolean') return 'boolean'
if (this.data instanceof Uint8Array) return 'bytes'
if (Array.isArray(this.data)) return 'array'
if (typeof this.data === 'object') return 'object'
throw new Error(`Encountered undefined type in value "${this.data}"`)
}
isString(): boolean {
return this.getType() === 'string'
}
asString(): string {
if (!this.isString()) {
throw new BadParamsError(`Expected data to be of type string, but found type ${this.getType()} at ${this.#contextPath}`)
}
// @ts-ignore check is above
return this.data
}
isBoolean(): boolean {
return this.getType() === 'boolean'
}
asBoolean(): boolean {
if (!this.isBoolean()) {
throw new BadParamsError(`Expected data to be of type boolean, but found type ${this.getType()} at ${this.#contextPath}`)
}
// @ts-ignore check is above
return this.data
}
isNumber(): boolean {
return this.getType() === 'number'
}
asNumber(): number {
if (!this.isNumber()) {
throw new BadParamsError(`Expected data to be of type number, but found type ${this.getType()} at ${this.#contextPath}`)
}
// @ts-ignore check is above
return this.data
}
isNull(): boolean {
return this.getType() === 'null'
}
asNull(): null {
if (!this.isNull()) {
throw new BadParamsError(`Expected data to be null, but found type ${this.getType()} at ${this.#contextPath}`)
}
// @ts-ignore check is above
return this.data
}
isBytes(): boolean {
return this.getType() === 'bytes'
}
asBytes(): Uint8Array {
if (!this.isBytes()) throw new Error(`Expected data to be a Uint8Array, but found type ${this.getType()}`)
// @ts-ignore check is above
return this.data
}
isArray(): boolean {
return this.getType() === 'array'
}
asArray(): SafeUnknownArray {
if (!this.isArray()) throw new Error(`Expected data to be an array, but found type ${this.getType()}`)
// @ts-ignore check is above
return new SafeUnknownArray(this.data)
}
isObject(): boolean {
return this.getType() === 'object'
}
asObject(): SafeUnknownObject {
if (!this.isObject()) throw new Error(`Expected data to be an object, but found type ${this.getType()}`)
// @ts-ignore check is above
return new SafeUnknownObject(this.data)
}
}
export class SafeUnknownObject {
data: Record<string, unknown>
#contextPath: string
constructor(data: Record<string, unknown>, contextPath = '$') {
this.data = data
this.#contextPath = contextPath
}
/** Gets an array of all the keys in the object */
keys(): string[] {
const indexes: string[] = []
for (const index in this.data) indexes.push(index)
return indexes
}
/** Gets an array of all the values in the array as safe unknowns */
values(): SafeUnknown[] {
const values: SafeUnknown[] = []
for (const key in this.data) values.push(new SafeUnknown(this.data[key]))
return values
}
/** Calls `fn` for every item in the array */
forEach(fn: (value: SafeUnknown, key: string) => unknown): void {
for (const key in this.data) fn(new SafeUnknown(this.data[key]), key)
}
/** Calls `fn` on each item in the array, returning a new array made up of the results of `fn` */
map<T>(fn: (value: SafeUnknown, key: string) => T): Record<string, T> {
const newRecord: Record<string, T> = {}
for (const key in this.data) newRecord[key] = fn(new SafeUnknown(this.data[key]), key)
return newRecord
}
/** Gets the value of a single key in the object. If the key doesn't exist, a `SafeUnknown` with `null` will be returned */
getSingle(key: string): SafeUnknown {
const value = this.data[key] ?? null
return new SafeUnknown(value, `${this.#contextPath}.${key}`)
}
/** Gets the value of a single key in the object. If the key doesn't exist, an error is thrown */
sureGetSingle(key: string): SafeUnknown {
const value = this.data[key]
if (value === undefined) throw new BadParamsError(`Expected to find a value for key "${key}" at ${this.#contextPath}`)
return new SafeUnknown(value, `${this.#contextPath}.${key}`)
}
/**
* Gets the value of an object path in the object. If a key doesn't exist, a `SafeUnknown` with `null` will be returned. If a key gives null,
* either by it not existing, or it actually being null, a `SafeUnknown` with `null` is immediately returned.
*
* Examples:
*
* ```ts
* new SafeUnknownObject({ foo: null }).get('foo', 'bar', 'bin', 'baz').isNull() // true
* new SafeUnknownObject({}).get('foo').isNull() // true
* new SafeUnknownObject({}).get('foo', 'bar', 'bin', 'baz').isNull() // true
* new SafeUnknownObject({ foo: "hello" }).get('foo', 'bar', 'bin', 'baz') // Error: Expected data to be an object, but found type string at $.foo
* new SafeUnknownObject({ foo: { bar: { bin: { baz: "Hello" }}}}).asString() // "Hello"
* ```
*/
get(...keys: string[]): SafeUnknown {
if (!keys.length) throw new Error('Expected at least 1 key to be provided')
const firstKey = keys[0]
const firstValue = this.getSingle(firstKey)
if (firstValue.isNull() || keys.length === 1) return firstValue
return firstValue.asObject().get(...keys.slice(1))
}
/**
* Gets the value of an object path in the object. If a key doesn't exist, an error is thrown. Unlike `get`, `null` is not
* immediately returned.
*
* Examples:
*
* ```ts
* new SafeUnknownObject({ foo: null }).sureGet('foo', 'bar', 'bin', 'baz') // Error: Expected data to be an object, but found type null at $.foo
* new SafeUnknownObject({}).sureGet('foo') // Error: Expected to find a value for key "foo" at $
* new SafeUnknownObject({}).sureGet('foo', 'bar', 'bin', 'baz').isNull() // Error: Expected to find a value for key "foo" at $
* new SafeUnknownObject({ foo: "hello" }).sureGet('foo', 'bar', 'bin', 'baz') // Error: Expected data to be an object, but found type string at $.foo
* new SafeUnknownObject({ foo: { bar: { bin: { baz: "Hello" }}}}).sureGet('foo', 'bar', 'bin', 'baz').asString() // "Hello"
* ```
*/
sureGet(...keys: string[]): SafeUnknown {
if (!keys.length) throw new Error('Expected at least 1 key to be provided')
const firstKey = keys[0]
const firstValue = this.sureGetSingle(firstKey)
if (keys.length === 1) return firstValue
return firstValue.asObject().get(...keys.slice(1))
}
}
export class SafeUnknownArray {
data: unknown[]
length: number
#contextPath: string
constructor(data: unknown[], contextPath = '$') {
this.data = data
this.length = data.length
this.#contextPath = contextPath
}
/** Gets an array of all the values in the array as safe unknowns */
values(): SafeUnknown[] {
const values: SafeUnknown[] = []
for (const value of this.data) values.push(new SafeUnknown(value))
return values
}
/** Calls `fn` for every item in the array */
forEach(fn: (value: SafeUnknown, index: number) => unknown): void {
for (const index in this.data) fn(new SafeUnknown(this.data[index]), parseInt(index))
}
/** Calls `fn` on each item in the array, returning a new array made up of the results of `fn` */
map<T>(fn: (value: SafeUnknown, index: number) => T): T[] {
const newArray: T[] = []
for (const index in this.data) newArray.push(fn(new SafeUnknown(this.data[index]), parseInt(index)))
return newArray
}
/** Gets the value of a single index in the array. If the index doesn't exist, a `SafeUnknown` with `null` will be returned */
get(index: number): SafeUnknown {
const value = this.data[index] ?? null
return new SafeUnknown(value, `${this.#contextPath}[${index}]`)
}
/** Gets the value of a single index in the array. If the index doesn't exist, an error is thrown */
sureGet(index: number): SafeUnknown {
const value = this.data[index]
if (value === undefined) throw new BadParamsError(`Expected to find an item for index "${index}" at ${this.#contextPath}`)
return new SafeUnknown(value, `${this.#contextPath}[${index}]`)
}
}