-
Notifications
You must be signed in to change notification settings - Fork 0
/
TypeRegistry.ts
50 lines (42 loc) · 1.24 KB
/
TypeRegistry.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
import { Is } from './Is'
import { Type } from './Type'
const Any: Type = {
default: undefined,
properties: {},
type: 'any',
typebase: 'object',
validator: (value: any) => true,
}
export class TypeRegistry {
private readonly registry: Map<string, Type>
constructor() {
this.registry = new Map<string, Type>()
}
public from(value: any): string {
const keys: string[] = Object.keys(Is)
for (const key of keys) {
const func = Is[key]
if (key !== 'any' && func(value)) {
return key
}
}
// We won't ever hit this because we can't create something
// that isn't a type of something to test.
/* istanbul ignore next */
throw new TypeError(`Could not parse for type: ${value}.`)
}
public register(type: Partial<Type>): TypeRegistry {
const baseType: Type = this.resolve(type.typebase || 'any')
const merged: Type = Object.assign({}, baseType, type)
this.registry.set(merged.type, merged)
return this
}
public resolve(name: string): Type {
const type = this.registry.get(name)
return type ? type : Any
}
public validate(value: any, type: string): boolean {
const typedef = this.resolve(type)
return typedef.validator(value, typedef.properties)
}
}