-
Notifications
You must be signed in to change notification settings - Fork 0
/
item.ts
345 lines (331 loc) · 10.1 KB
/
item.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
/* eslint-disable @typescript-eslint/ban-types */
import 'reflect-metadata';
import { define } from '@biorate/tools';
import { DateTime } from 'luxon';
import { isObject } from 'lodash';
import { Props, Types } from './symbols';
import { action } from './decorators';
const _defineClass = Symbol('#defineClass');
const _setType = Symbol('#setType');
const _getType = Symbol('#getType');
const _setData = Symbol('#setData');
const _validate = Symbol('#validate');
/**
* @description
* The [Item](https://biorate.github.io/core/classes/collection.item.html)
* extensions is designed to form the structure of the object, solve the problem of application architecture,
* dependency injection and inversion of control.
*
* ### Features:
* - cast to type properties
* - DI
* - IoC
*
* @example
* ```
* import * as collection from '@biorate/collection';
* const { embed, singletone } = collection;
* const BindedSymbol = Symbol('Binded');
*
* @singletone()
* class Binded {
* public hello = 'world!';
* }
*
* class Nested extends collection.Item {
* @embed(Nested.Map) public map: Map<any, any> = null;
* @embed(Nested.Set) public itemSet: Set<any> = null;
* @embed(BindedSymbol) public binded: Binded = null;
* }
*
* class Item extends collection.Item {
* @embed(Item.Int) public int: number = null;
* @embed(Item.Float) public float: number = null;
* @embed(Item.String) public string: string = null;
* @embed(Item.Bool) public bool: boolean = null;
* @embed(Item.Date) public date: Date = null;
* @embed(Item.Array) public array: number[] = null;
* @embed(Item.Object) public object: Record<string, any> = null;
* @embed(Item.Json) public json: Record<string, any> = null;
* @embed(Nested) public nested: Nested = null;
* @embed(BindedSymbol) public binded: Binded = null;
* }
*
* Item.bind(BindedSymbol, Binded);
*
* const data = {
* int: 1,
* float: 1.1,
* string: 'test',
* bool: true,
* date: new Date(),
* array: [1, 2, 3],
* object: { a: 1, b: 2 },
* json: '{"test": 1}',
* nested: {
* map: [
* [1, 'a'],
* [2, 'b'],
* ],
* itemSet: [1, 2, 3],
* },
* };
*
* const item = new Item();
*
* item.initialize(data);
*
* console.log(item);
* // Item {
* // int: 1,
* // float: 1.1,
* // string: 'test',
* // bool: true,
* // date: 2021-05-19T06:42:26.049Z,
* // array: [ 1, 2, 3 ],
* // object: { a: 1, b: 2 },
* // json: { test: 1 },
* // nested: Nested {
* // map: Map { 1 => 'a', 2 => 'b' },
* // itemSet: Set { 1, 2, 3 },
* // binded: Binded { hello: 'world!' }
* // }
* // }
*
* console.log(item.binded === item.nested.binded); // true
* ```
*/
export abstract class Item<P = { parent?: any }> {
/** @description cast to **int** type symbol */
public static readonly Int = Types.Int;
/** @description cast to **string** type symbol */
public static readonly String = Types.String;
/** @description cast to **float** type symbol */
public static readonly Float = Types.Float;
/** @description cast to **boolean** type symbol */
public static readonly Bool = Types.Bool;
/** @description cast to **Date** type symbol */
public static readonly Date = Types.Date;
/** @description cast to **Object** type symbol */
public static readonly Object = Types.Object;
/** @description cast to **Array** type symbol */
public static readonly Array = Types.Array;
/** @description cast to **JSON** type symbol */
public static readonly Json = Types.Json;
/** @description cast to **Map** type symbol */
public static readonly Map = Types.Map;
/** @description cast to **Set** type symbol */
public static readonly Set = Types.Set;
/** @description cast to **Luxon** type symbol */
public static readonly Luxon = Types.Luxon;
/** @description Binding map, for IoC pattern realization */
public static readonly bindings = new Map<string | symbol | Function, Function>();
/**
* @description Bind string, symbol, or Class to Class
* @param key - dependency identifier
* @param val - dependency Class
* */
public static bind(key: string | symbol | Function, val: Function) {
return this.bindings.set(key, val);
}
/**
* @description Instantiate and initialize class
* @param data - data object
* @param field - object field
* @param Class - Instance class
* */
[_defineClass] = (
data: Record<string, any>,
field: string,
Class: new (...args: any[]) => any,
) => {
if (!(this[field] instanceof Class)) this[field] = new Class(data[field], this);
this[field].initialize?.(data[field]);
};
/**
* @description Cache type
* @param data - data object
* @param field - object field
* */
[_setType] = (data: Record<string, any>, field: string) => {
if (!(field in this[Props.types])) this[Props.types][field] = this[field];
};
/**
* @description Get type from cache
* @param data - data object
* @param field - object field
* */
[_getType] = (data: Record<string, any>, field: string) => {
let type = Reflect.getMetadata(Props.Class, Object.getPrototypeOf(this), field);
if (!type) type = this[Props.types][field];
if (Item.bindings.has(type)) type = Item.bindings.get(type);
return type;
};
/**
* @description Cast to type and set data value
* @param data - data object
* @param field - object field
* */
[_setData] = (data: Record<string, any>, field: string) => {
const type = this[_getType](data, field);
const items = Array.isArray(data[field]) ? data[field] : [];
switch (type) {
case Item.Int:
(<number>this[field]) = parseInt(data[field], 10) || 0;
break;
case Item.Float:
(<number>this[field]) = parseFloat(data[field]) || 0;
break;
case Item.Bool:
(<boolean>this[field]) = Boolean(data[field]);
break;
case Item.Date:
(<Date>this[field]) = new Date(data[field]);
break;
case Item.Luxon:
(<DateTime>this[field]) =
data[field] instanceof Date
? DateTime.fromJSDate(data[field])
: typeof data[field] === 'string'
? DateTime.fromISO(data[field])
: DateTime.fromMillis(data[field]);
break;
case Item.Object:
(<Object>this[field]) = isObject(data[field]) ? data[field] : {};
break;
case Item.Array:
(<unknown[]>this[field]) = Array.isArray(data[field]) ? data[field] : [];
break;
case Item.Json:
try {
(<Object>this[field]) = JSON.parse(data[field]);
} catch (e) {
(<Object>this[field]) = null;
}
break;
case Item.String:
(<string>this[field]) = data[field] ? String(data[field]) : '';
break;
case Item.Map:
this[Props.defineMapOrSet](field, items, Map);
break;
case Item.Set:
this[Props.defineMapOrSet](field, items, Set);
break;
default:
if (type instanceof Function) {
this[_defineClass](data, field, type);
} else {
if (field in data) this[field] = data[field];
}
break;
}
};
/**
* @description Cache type and apply data value
* @param data - data object
* @param field - object field
* */
[_validate] = (data: Record<string, any>, field: string) => {
data = data || {};
this[_setType](data, field);
this[_setData](data, field);
};
[Props.defineMapOrSet](
field: string,
items: any[],
Ctor: { new (...args: any[]): any },
) {
if (
!this[field] ||
typeof this[field] !== 'object' ||
(!('add' in this[field]) && !('set' in this[field]))
)
this[field] = new Ctor(items);
else
items.forEach((item) =>
this[field].set ? this[field].set(...item) : this[field].add(item),
);
}
/**
* @param data - data object
* @param parent - parent item
* @example
* ```
* import * as collection from '@biorate/collection';
*
* class Item extends collection.Item {
* @embed(Item.Int) public id: number = null;
* @embed(Item.String) public title: string = null;
* }
*
* const item = new Item().initialize({ id: 1, title: 'one' });
* ```
*/
public constructor(data: Record<string, any> = null, parent: P = null) {
define.prop(this)(Props.parent, parent, 'c')(Props.types, {}, 'w')(
Props.data,
data,
'w',
);
}
/**
* @description Initialize object properties
* @param data - data object
* @example
* ```
* import * as collection from '@biorate/collection';
*
* class Item extends collection.Item {
* @embed(Item.Int) public id: number = null;
* @embed(Item.String) public title: string = null;
* }
*
* const item = new Item();
* console.log(item); // Item { id: null, title: null }
* item.initialize({ id: 1, title: 'one' });
* console.log(item); // Item { id: 1, title: 'one' }
* item.initialize({ id: 2, title: 'two' });
* console.log(item); // Item { id: 2, title: 'two' }
* ```
*/
@action() public initialize(data: Record<string, any> = this[Props.data]) {
(<Record<string, any>>this[Props.data]) = data;
for (const field in this) {
if (!(field in this)) continue;
this[_validate](data, field);
}
return this;
}
/**
* @description Change data values
* @param data - data object
*
* @example
* ```
* import * as collection from '@biorate/collection';
*
* class Item extends collection.Item {
* @embed(Nested.Int) public int: number = null;
* @embed(Nested.String) public string: string = null;
* }
*
* const item = new Item().initialize({ int: 1, string: 'test' }});
* item.set({ int: 2, string: 'hello' }});
* console.log(item); // Item { int: 2, string: 'hello' }
* ```
*/
@action() public set(data: Record<string, any>) {
for (const field in data) {
if (!(field in this)) continue;
this[_validate](data, field);
}
return this;
}
/**
* @description Alias to parent class
*/
public get parent(): P {
return this[Props.parent];
}
}