-
Notifications
You must be signed in to change notification settings - Fork 0
/
Schema.ts
427 lines (365 loc) · 10.8 KB
/
Schema.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
import {
ErrorCode,
IInvalidFieldErrorOptions,
IInvalidFieldError
} from './errors/error.types'
import SpruceError from './errors/SpruceError'
import FieldFactory from './factories/FieldFactory'
import { ISchemaFieldDefinition } from './fields'
import {
ISchemaDefinition,
SchemaDefinitionPartialValues,
SchemaFields,
SchemaFieldNames,
ISchemaNormalizeOptions,
SchemaFieldDefinitionValueType,
ISchemaValidateOptions,
SchemaDefinitionDefaultValues,
ISchemaGetValuesOptions,
SchemaDefinitionAllValues,
ISchemaNamedFieldsOptions,
ISchemaNamedField,
ISchemaGetDefaultValuesOptions,
FieldNamesWithDefaultValueSet,
ISchema,
IField,
IDefinitionsById
} from './schema.types'
/** Universal schema class */
export default class Schema<S extends ISchemaDefinition> implements ISchema<S> {
/** Should i do a duplicate check on schemas when tracking globally? */
public static enableDuplicateCheckWhenTracking = true
/** Global definition hash for lookups by id */
private static definitionsById: IDefinitionsById = {}
/** Our unique id */
public get schemaId() {
return this.definition.id
}
public get version() {
return this.definition.version
}
public get description() {
return this.definition.id
}
/** The schema definition */
private definition: S
/** The values of this schema */
public values: SchemaDefinitionPartialValues<S>
/** All the field objects keyed by field name, use getField rather than accessing this directly */
private fields: SchemaFields<S>
/** For caching getNamedFields() */
// private namedFieldCache: ISchemaNamedField<T>[] | undefined
public constructor(definition: S, values?: SchemaDefinitionPartialValues<S>) {
this.definition = definition
this.values = values ? values : {}
// Pull field definitions off schema definition
const fieldDefinitions = this.definition.fields
if (!fieldDefinitions) {
throw new Error(`Schemas don't support dynamic fields yet`)
}
// Empty fields to start
this.fields = {} as SchemaFields<S>
Object.keys(fieldDefinitions).forEach(name => {
const definition = fieldDefinitions[name]
const field = FieldFactory.field(name, definition)
// TODO why do i have to cast to any?
this.fields[name as SchemaFieldNames<S>] = field as any
if (definition.value) {
this.set(name as SchemaFieldNames<S>, definition.value)
}
})
}
public static trackDefinition(definition: ISchemaDefinition) {
this.validateDefinition(definition)
const id = definition.id
if (!this.definitionsById[id]) {
this.definitionsById[id] = []
}
this.definitionsById[id].push(definition)
}
public static forgetDefinition(id: string) {
delete Schema.definitionsById[id]
}
public static forgetAllDefinitions() {
this.definitionsById = {}
}
public static getDefinition(
id: string,
version?: string
): ISchemaDefinition | undefined {
if (!this.definitionsById[id]) {
throw new SpruceError({
code: ErrorCode.SchemaNotFound,
schemaId: id
})
}
const match = this.definitionsById[id].find(d => d.version === version)
if (!match) {
throw new SpruceError({
code: ErrorCode.VersionNotFound
})
}
return match
}
public static getTrackingCount() {
return Object.keys(this.definitionsById).length
}
public static areDefinitionsTheSame(
left: ISchemaDefinition,
right: ISchemaDefinition
): boolean {
if (left.id !== right.id) {
return false
}
const fields1 = Object.keys(left.fields ?? {}).sort()
const fields2 = Object.keys(right.fields ?? {}).sort()
if (fields1.join('|') !== fields2.join('|')) {
return false
}
// TODO let fields compare their definitions
return true
}
/** Tells you if a schema definition is valid */
public static isDefinitionValid(
definition: unknown
): definition is ISchemaFieldDefinition {
try {
Schema.validateDefinition(definition)
return true
} catch {
return false
}
}
/** Throws a field validation error */
public static validateDefinition(
definition: any
): asserts definition is ISchemaDefinition {
const errors: string[] = []
if (!definition) {
errors.push('definition_empty')
} else {
if (!definition.id) {
errors.push('id_missing')
} else if (!(typeof definition.id === 'string')) {
errors.push('id_not_string')
}
if (!definition.name) {
errors.push('name_missing')
} else if (!(typeof definition.name === 'string')) {
errors.push('name_not_string')
}
if (!definition.fields && !definition.dynamicKeySignature) {
errors.push('needs_fields_or_dynamic_key_signature')
}
}
if (errors.length > 0) {
throw new SpruceError({
code: ErrorCode.InvalidSchemaDefinition,
schemaId: definition?.id ?? 'ID MISSING',
errors
})
}
}
/** Normalize a value against a field. runs through valueType transformer and makes an array if isArray is true */
public normalizeValue<
F extends SchemaFieldNames<S>,
CreateSchemaInstances extends boolean = true
>(
forField: F,
value: any,
options?: ISchemaNormalizeOptions<S, CreateSchemaInstances>
): SchemaFieldDefinitionValueType<S, F, CreateSchemaInstances> {
// If the value is not null or undefined, coerce it into an array
let localValue =
value === null || typeof value === 'undefined'
? ([] as SchemaFieldDefinitionValueType<S, F>)
: Array.isArray(value)
? value
: [value]
if (!Array.isArray(localValue)) {
throw new SpruceError({
code: ErrorCode.InvalidField,
schemaId: this.definition.id,
errors: [{ name: forField, code: 'value_not_array' }]
})
}
const { validate = true, createSchemaInstances = true, byField } =
options ?? {}
// Get field && override options by that field
const field = this.fields[forField]
const overrideOptions = byField?.[forField] ?? {}
// Validate if we're supposed to
let errors: IInvalidFieldError[] = []
if (validate) {
localValue.forEach(value => {
errors = [
...errors,
...field.validate(value, {
definitionsById: Schema.definitionsById,
...(field.definition.options ?? {}),
...overrideOptions
})
]
})
}
// If there are any errors, bail
if (errors.length > 0) {
throw new SpruceError({
code: ErrorCode.InvalidField,
schemaId: this.definition.id,
errors
})
}
// If there is a value, transform it to it's expected value
// Is array will always pass here
if (localValue.length > 0) {
localValue = localValue.map(value =>
typeof value === 'undefined'
? undefined
: (field as IField<any>).toValueType(value, {
definitionsById: Schema.definitionsById,
createSchemaInstances,
...(field.definition.options ?? {}),
...overrideOptions
})
)
}
return (field.isArray
? localValue
: localValue[0]) as SchemaFieldDefinitionValueType<
S,
F,
CreateSchemaInstances
>
}
/** Get any field by name */
public get<
F extends SchemaFieldNames<S>,
CreateSchemaInstances extends boolean = true
>(
fieldName: F,
options: ISchemaNormalizeOptions<S, CreateSchemaInstances> = {}
): SchemaFieldDefinitionValueType<S, F, CreateSchemaInstances> {
// Get value off self
const value: SchemaFieldDefinitionValueType<S, F> | undefined | null =
this.values[fieldName] !== undefined ? this.values[fieldName] : undefined
return this.normalizeValue(fieldName, value, options)
}
/** Set a value and ensure its type */
public set<F extends SchemaFieldNames<S>>(
fieldName: F,
value: SchemaFieldDefinitionValueType<S, F>,
options: ISchemaNormalizeOptions<S, false> = {}
): this {
// If the value is not null or undefined, coerce it into an array
const localValue = this.normalizeValue(fieldName, value, options)
this.values[fieldName] = localValue
return this
}
/** Is this schema valid? */
public isValid() {
try {
this.validate()
return true
} catch {
return false
}
}
/** Returns an array of schema validation errors */
public validate(options: ISchemaValidateOptions<S> = {}) {
const errors: IInvalidFieldErrorOptions['errors'] = []
this.getNamedFields(options).forEach(item => {
const { name, field } = item
const value = this.get(name, { validate: false })
const fieldErrors = field.validate(value, {
definitionsById: Schema.definitionsById
})
if (fieldErrors.length > 0) {
errors.push(...fieldErrors)
}
})
if (errors.length > 0) {
throw new SpruceError({
code: ErrorCode.InvalidField,
schemaId: this.definition.id,
errors
})
}
}
/** Get all default values based on the definition */
public getDefaultValues<
F extends FieldNamesWithDefaultValueSet<S> = FieldNamesWithDefaultValueSet<
S
>,
CreateSchemaInstances extends boolean = true
>(
options: ISchemaGetDefaultValuesOptions<S, F, CreateSchemaInstances> = {}
): Pick<SchemaDefinitionDefaultValues<S, CreateSchemaInstances>, F> {
const values: Partial<SchemaDefinitionDefaultValues<S>> = {}
this.getNamedFields().forEach(namedField => {
const { name, field } = namedField
if (typeof field.definition.defaultValue !== 'undefined') {
// TODO how to type name so it works as key of values
// @ts-ignore
values[name] = this.normalizeValue(
name,
field.definition.defaultValue,
options
)
}
})
return values as Pick<
SchemaDefinitionDefaultValues<S, CreateSchemaInstances>,
F
>
}
/** Get all values valued */
public getValues<
F extends SchemaFieldNames<S> = SchemaFieldNames<S>,
CreateSchemaInstances extends boolean = true
>(
options: ISchemaGetValuesOptions<S, F, CreateSchemaInstances> = {}
): Pick<SchemaDefinitionAllValues<S, CreateSchemaInstances>, F> {
const values: SchemaDefinitionPartialValues<S, CreateSchemaInstances> = {}
const { fields = Object.keys(this.fields) } = options
this.getNamedFields().forEach(namedField => {
const { name } = namedField
if (fields.indexOf(name) > -1) {
const value = this.get(name, options)
values[name] = value
}
})
// We know this conforms after the loop above, nothing to do here
return values as Pick<
SchemaDefinitionAllValues<S, CreateSchemaInstances>,
F
>
}
/** Set a bunch of values at once */
public setValues(values: SchemaDefinitionPartialValues<S>): this {
this.getNamedFields().forEach(namedField => {
const { name } = namedField
const value = values[name]
if (typeof value !== 'undefined') {
// TODO why cast? types should map by here
this.set(name, value as any)
}
})
return this
}
public getNamedFields<F extends SchemaFieldNames<S>>(
options: ISchemaNamedFieldsOptions<S, F> = {}
): ISchemaNamedField<S>[] {
const namedFields: ISchemaNamedField<S>[] = []
const { fields = Object.keys(this.fields) as F[] } = options
fields.forEach(name => {
const field = this.fields[name]
namedFields.push({ name, field })
})
return namedFields
}
public getField<F extends SchemaFieldNames<S>>(name: F) {
const field = this.fields[name]
return field
}
}