forked from greg9504/ts-json-serializer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Resolver.ts
89 lines (80 loc) · 2.13 KB
/
Resolver.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
import { DuplicateTypeRegistration } from './errors';
import { SerializableType } from './SerializableType';
/**
* Resolving instance. Holds the registered types and is the central type "database" for the system.
*
* @export
* @class Resolver
*/
export class Resolver {
private static _instance: Resolver;
/**
* Actual instance (singleton).
*
* @readonly
* @static
* @type {Resolver}
* @memberOf Resolver
*/
public static get instance(): Resolver {
if (!Resolver._instance) {
Resolver._instance = new Resolver();
}
return Resolver._instance;
}
/**
* Hashmap of registered types.
*
* @private
* @type {{ [name: string]: SerializableType }}
* @memberOf Resolver
*/
private types: { [name: string]: SerializableType<any> } = {};
private constructor() { }
/**
* Resets the registered types.
* May be useful for unit testing.
*
* @memberOf Resolver
*/
public reset(): void {
this.types = {};
}
/**
* Add a type to the resolver. Throws if the type is already registered.
*
* @param {SerializableType} model
*
* @memberOf Resolver
*/
public addType(type: SerializableType<any>): void {
if (this.types[type.name]) {
throw new DuplicateTypeRegistration(type.name);
}
this.types[type.name] = type;
}
/**
* Searches and returns a type by name.
*
* @param {string} name
* @returns {(SerializableType | undefined)}
*
* @memberOf Resolver
*/
public getType(name: string): SerializableType<any> | undefined {
return this.types[name];
}
/**
* Searches and returns a type by a given object (does compare the contructors).
*
* @param {*} obj
* @returns {(SerializableType | undefined)}
*
* @memberOf Resolver
*/
public getTypeByObject(obj: any): SerializableType<any> | undefined {
return Object.keys(this.types)
.map(key => this.types[key])
.find(o => obj.constructor === o.ctor);
}
}