-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOwom.ts
76 lines (62 loc) · 2 KB
/
Owom.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
import { IConstructorOptions } from "types/IConstructorOptions";
import { DiResolver, Options } from "types/Options";
import { MapManyFunc, MapOneFunc } from "types/Map";
import { Constructor } from "types/Constructor";
import { IOwom } from "types/IOwom";
export class Owom implements IOwom {
private _diResolver?: DiResolver;
constructor(options?: Options) {
if (!options) {
return;
}
const { di } = options;
if (di) {
this._diResolver = di;
}
}
map<T, Z>(entity: T): { to: MapOneFunc<T, Z> };
map<T, Z>(entity: T[]): { to: MapManyFunc<T, Z> };
map<T, Z>(
entity: T | T[],
): { to: MapOneFunc<T, Z> } | { to: MapManyFunc<T, Z> } {
return {
to: (Mapper, options) => {
if (typeof Mapper === "string") {
return this._resolveWithDi<T>(entity, Mapper, options);
}
return this._resolveWithConcreteType<T, Z>(entity, Mapper, options);
},
};
}
private _resolveWithConcreteType<T, Z>(
entity: T | T[],
Mapper: Constructor<T, Z>,
options?: IConstructorOptions,
) {
return Array.isArray(entity)
? entity.map(entity => this._executeMap(entity, Mapper, options))
: this._executeMap(entity, Mapper, options);
}
private _resolveWithDi<T>(
entity: T | T[],
token: string,
options?: IConstructorOptions,
) {
const Mapper = this._diResolver(token);
return Array.isArray(entity)
? entity.map(entity => this._executeMap(entity, Mapper, options))
: this._executeMap(entity, Mapper, options);
}
private _executeMap<T, Z>(
entity: T,
Mapper: Constructor<T, Z>,
options?: IConstructorOptions,
) {
const defaultOptions: IConstructorOptions = { additionalData: {} };
const mapper = new Mapper(entity, this, options ?? defaultOptions);
// @NOTE here you can cover extra options, referring to Mapper instance
mapper._.removeTemporaryData();
// @NOTE free to cast as outcome of Mapper instantiation is supposed to match "Z"
return <Z>mapper;
}
}