@dipscope/type-manager 5.0.0-beta.1 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/CHANGELOG.md +224 -224
  2. package/LICENSE.md +201 -201
  3. package/README.md +1857 -1846
  4. package/alias.d.ts +6 -6
  5. package/custom-data.d.ts +6 -6
  6. package/default-value-resolver.d.ts +7 -7
  7. package/default-value.d.ts +7 -7
  8. package/discriminant.d.ts +8 -8
  9. package/discriminator.d.ts +6 -6
  10. package/factories/index.d.ts +1 -1
  11. package/factories/type-factory.d.ts +19 -19
  12. package/factory.d.ts +18 -18
  13. package/functions/get-own-reflect-metadata.d.ts +9 -9
  14. package/functions/get-reflect-metadata.d.ts +10 -10
  15. package/functions/get-words.d.ts +8 -8
  16. package/functions/index.d.ts +16 -16
  17. package/functions/is-arrow-function.d.ts +8 -8
  18. package/functions/is-ctor-function.d.ts +8 -8
  19. package/functions/is-data-view.d.ts +8 -8
  20. package/functions/is-float-32-array.d.ts +8 -8
  21. package/functions/is-float-64-array.d.ts +8 -8
  22. package/functions/is-int-16-array.d.ts +8 -8
  23. package/functions/is-int-32-array.d.ts +8 -8
  24. package/functions/is-int-8-array.d.ts +8 -8
  25. package/functions/is-uint-16-array.d.ts +8 -8
  26. package/functions/is-uint-32-array.d.ts +8 -8
  27. package/functions/is-uint-8-array.d.ts +8 -8
  28. package/functions/is-uint-8-clamped-array.d.ts +8 -8
  29. package/functions/name-of.d.ts +8 -8
  30. package/generic-argument.d.ts +7 -7
  31. package/generic-metadata.d.ts +7 -7
  32. package/index.d.ts +54 -54
  33. package/index.js +1 -1
  34. package/inject-index.d.ts +6 -6
  35. package/inject-metadata.d.ts +88 -72
  36. package/inject-options.d.ts +22 -22
  37. package/inject.d.ts +10 -10
  38. package/injector.d.ts +16 -16
  39. package/injectors/index.d.ts +1 -1
  40. package/injectors/singleton-injector.d.ts +31 -31
  41. package/log-level.d.ts +11 -11
  42. package/log.d.ts +95 -95
  43. package/metadata.d.ts +42 -42
  44. package/naming-convention.d.ts +15 -15
  45. package/naming-conventions/camel-case-naming-convention.d.ts +26 -26
  46. package/naming-conventions/flat-case-naming-convention.d.ts +25 -25
  47. package/naming-conventions/flat-upper-case-naming-convention.d.ts +25 -25
  48. package/naming-conventions/index.d.ts +8 -8
  49. package/naming-conventions/kebab-case-naming-convention.d.ts +26 -26
  50. package/naming-conventions/kebab-upper-case-naming-convention.d.ts +26 -26
  51. package/naming-conventions/pascal-case-naming-convention.d.ts +26 -26
  52. package/naming-conventions/snake-case-naming-convention.d.ts +26 -26
  53. package/naming-conventions/snake-upper-case-naming-convention.d.ts +26 -26
  54. package/package.json +55 -51
  55. package/property-metadata.d.ts +309 -196
  56. package/property-name.d.ts +6 -6
  57. package/property-options.d.ts +116 -116
  58. package/property.d.ts +13 -13
  59. package/reference-callback.d.ts +7 -7
  60. package/reference-handler.d.ts +31 -31
  61. package/reference-handlers/direct-reference-handler.d.ts +32 -32
  62. package/reference-handlers/index.d.ts +3 -3
  63. package/reference-handlers/lead-reference-handler.d.ts +33 -33
  64. package/reference-handlers/path-reference-handler.d.ts +55 -55
  65. package/reference-key.d.ts +6 -6
  66. package/reference-value-getter.d.ts +7 -7
  67. package/reference-value-setter.d.ts +7 -7
  68. package/reference-value.d.ts +6 -6
  69. package/serializer-context-options.d.ts +43 -43
  70. package/serializer-context.d.ts +410 -362
  71. package/serializer.d.ts +27 -27
  72. package/serializers/array-buffer-serializer.d.ts +28 -28
  73. package/serializers/array-serializer.d.ts +28 -28
  74. package/serializers/boolean-serializer.d.ts +37 -37
  75. package/serializers/data-view-serializer.d.ts +28 -28
  76. package/serializers/date-serializer.d.ts +28 -28
  77. package/serializers/float-32-array-serializer.d.ts +28 -28
  78. package/serializers/float-64-array-serializer.d.ts +28 -28
  79. package/serializers/index.d.ts +19 -19
  80. package/serializers/int-16-array-serializer.d.ts +28 -28
  81. package/serializers/int-32-array-serializer.d.ts +28 -28
  82. package/serializers/int-8-array-serializer.d.ts +28 -28
  83. package/serializers/map-serializer.d.ts +28 -40
  84. package/serializers/number-serializer.d.ts +37 -37
  85. package/serializers/set-serializer.d.ts +28 -28
  86. package/serializers/string-serializer.d.ts +37 -37
  87. package/serializers/type-serializer.d.ts +28 -28
  88. package/serializers/uint-16-array-serializer.d.ts +28 -28
  89. package/serializers/uint-32-array-serializer.d.ts +28 -28
  90. package/serializers/uint-8-array-serializer.d.ts +28 -28
  91. package/serializers/uint-8-clamped-array-serializer.d.ts +28 -28
  92. package/type-abstraction.d.ts +8 -8
  93. package/type-argument.d.ts +9 -9
  94. package/type-context-entry.d.ts +36 -36
  95. package/type-context.d.ts +58 -58
  96. package/type-ctor.d.ts +6 -6
  97. package/type-fn.d.ts +8 -8
  98. package/type-like.d.ts +7 -7
  99. package/type-manager-options.d.ts +24 -24
  100. package/type-manager.d.ts +331 -331
  101. package/type-metadata-resolver.d.ts +8 -8
  102. package/type-metadata-symbol.d.ts +6 -6
  103. package/type-metadata.d.ts +472 -322
  104. package/type-name.d.ts +6 -6
  105. package/type-options-base.d.ts +90 -90
  106. package/type-options.d.ts +79 -79
  107. package/type-resolver.d.ts +7 -7
  108. package/type.d.ts +9 -9
package/README.md CHANGED
@@ -1,1846 +1,1857 @@
1
- # TypeManager.TS
2
-
3
- ![GitHub](https://img.shields.io/github/license/dipscope/TypeManager.TS) ![NPM](https://img.shields.io/npm/v/@dipscope/type-manager) ![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg)
4
-
5
- Type manager is a parsing package for `TypeScript` which will help you to transform JSON strings or plain objects into `JavaScript` object instances. It supports [decorators](https://www.typescriptlang.org/docs/handbook/decorators.html) or declarative configuration and allows you to configure parsing of your or 3rd party classes easily.
6
-
7
- We recommend to use our [official website](https://dipscope.com/type-manager/what-issues-it-solves) to navigate through available features. You can also use the latest documentation described below.
8
-
9
- ## Give a star :star:
10
-
11
- If you like or are using this project please give it a star. Thanks!
12
-
13
- ## Table of contents
14
-
15
- * [What issues it solves?](#what-issues-it-solves)
16
- * [Installation](#installation)
17
- * [How it works?](#how-it-works)
18
- * [Defining decorators](#defining-decorators)
19
- * [Type decorator](#type-decorator)
20
- * [Property decorator](#property-decorator)
21
- * [Inject decorator](#inject-decorator)
22
- * [Defining decorator options](#defining-decorator-options)
23
- * [Alias option](#alias-option)
24
- * [Custom data option](#custom-data-option)
25
- * [Default value option](#default-value-option)
26
- * [Deserializable option](#deserializable-option)
27
- * [Discriminant option](#discriminant-option)
28
- * [Discriminator option](#discriminator-option)
29
- * [Factory option](#factory-option)
30
- * [Injectable option](#injectable-option)
31
- * [Injector option](#injector-option)
32
- * [Naming convention option](#naming-convention-option)
33
- * [Preserve discriminator option](#preserve-discriminator-option)
34
- * [Preserve null option](#preserve-null-option)
35
- * [Reference handler option](#reference-handler-option)
36
- * [Serializable option](#serializable-option)
37
- * [Serializer option](#serializer-option)
38
- * [Use default value option](#use-default-value-option)
39
- * [Use implicit conversion option](#use-implicit-conversion-option)
40
- * [Defining configuration manually](#defining-configuration-manually)
41
- * [Configuring global options](#configuring-global-options)
42
- * [Configuring options per type](#configuring-options-per-type)
43
- * [Configuring usage of polymorphic types](#configuring-usage-of-polymorphic-types)
44
- * [Configuring naming convention](#configuring-naming-convention)
45
- * [Configuring reference handler](#configuring-reference-handler)
46
- * [Advanced usage](#advanced-usage)
47
- * [Defining custom data](#defining-custom-data)
48
- * [Defining custom serializer](#defining-custom-serializer)
49
- * [Defining custom injector](#defining-custom-injector)
50
- * [Defining custom factory](#defining-custom-factory)
51
- * [Defining custom naming convention](#defining-custom-naming-convention)
52
- * [Use cases](#use-cases)
53
- * [Built in serializers](#built-in-serializers)
54
- * [Circular object references](#circular-object-references)
55
- * [Dependency injection and immutable types](#dependency-injection-and-immutable-types)
56
- * [Different case usage in class and JSON](#different-case-usage-in-class-and-json)
57
- * [Enum types](#enum-types)
58
- * [Generic types](#generic-types)
59
- * [Integration with Angular](#integration-with-angular)
60
- * [Polymorphic types](#polymorphic-types)
61
- * [Versioning](#versioning)
62
- * [Contributing](#contributing)
63
- * [Authors](#authors)
64
- * [Notes](#notes)
65
- * [License](#license)
66
-
67
- ## What issues it solves?
68
-
69
- In `JavaScript` there are two types of objects:
70
-
71
- * Plain objects which are created using `{}` notation;
72
- * Constructor based objects which are created using `new Class()` notation.
73
-
74
- Sometimes we want to transform plain objects to the classes we have. Let's assume we are loading a users JSON data from our backend API or the other datasource:
75
-
76
- ```json
77
- [
78
- {
79
- "id": 1,
80
- "name": "Dmitry",
81
- "deletedAt": "2021-02-22T20:15:00.000Z"
82
- },
83
- {
84
- "id": 2,
85
- "name": "Alex",
86
- "deletedAt": null
87
- },
88
- {
89
- "id": 3,
90
- "name": "Anna",
91
- "deletedAt": null
92
- }
93
- ]
94
- ```
95
-
96
- We have a `User` class:
97
-
98
- ```typescript
99
- export class User
100
- {
101
- public id: number;
102
- public name: string;
103
- public deletedAt: Date;
104
-
105
- public constructor(id: number, name: string)
106
- {
107
- this.id = id;
108
- this.name = name;
109
-
110
- return;
111
- }
112
-
113
- public isDeleted(): boolean
114
- {
115
- return this.deletedAt !== null;
116
- }
117
- }
118
- ```
119
-
120
- Somewhere in code we are checking if user is deleted before performing some action.
121
-
122
- ```typescript
123
- const users: User[] = JSON.parse(usersJson);
124
-
125
- for (const user of users)
126
- {
127
- if (user.isDeleted())
128
- {
129
- // Do some action...
130
- }
131
- }
132
- ```
133
-
134
- Do you see the problem in this piece of code?
135
-
136
- `JSON.parse` function returns plain objects and we actually lied to compiler when said that it is a `User` class array. In this code we can successfully use `user.id` or `user.name`. However we cannot use `user.isDeleted()` because user is not an instance of a `User` class.
137
-
138
- So what to do? How to get `User` array from our JSON?
139
-
140
- Solution is to create new instances of `User` class from plain objects returned by `JSON.parse` function. But things may go wrong once you have a more complex object hierarchy. Besides `deletedAt` property is represented as `String` in JSON but `User` class declares it as a `Date` so we also have to perform appropriate conversion when assigning this property.
141
-
142
- There exists much more simple way. Let's use our `TypeManager` for getting instances of `User` class from JSON:
143
-
144
- ```typescript
145
- import { TypeManager } from '@dipscope/type-manager';
146
-
147
- const users: User[] = TypeManager.parse(User, usersJson);
148
-
149
- for (const user of users)
150
- {
151
- if (user.isDeleted())
152
- {
153
- // Do some action...
154
- }
155
- }
156
- ```
157
-
158
- Now we can use all power provided by `JavaScript` class instances. Want to know more? Let's dive into the details.
159
-
160
- ## Installation
161
-
162
- `TypeManager.TS` is available from NPM, both for browser (e.g. using webpack) and NodeJS:
163
-
164
- ```
165
- npm i @dipscope/type-manager
166
- ```
167
-
168
- TypeScript needs to run with the `experimentalDecorators` and `emitDecoratorMetadata` options enabled when using decorator annotations. So make sure you have properly configured your `tsconfig.json` file.
169
-
170
- _If you want additional type-safety and reduced syntax you may wish to install [reflect-metadata](https://github.com/rbuckton/reflect-metadata). This step is on your choice and fully optional. When installed it must be available globally to work. This can usually be done with `import 'reflect-metadata';` in your main index file._
171
-
172
- ## How it works?
173
-
174
- It defines configuration for each object which you are going to serialize or deserialize and uses this configuration to process data of your choice. There are two possible ways to define a configuration:
175
-
176
- * Using decorator annotations;
177
- * Using declarative style;
178
-
179
- The first one is the easiest and can be used for any class you control. If you want to configure serialization of 3rd party classes, global options or you don't like decorators it is better to go with the second. There are no restrictions to use one or another. You can combine two ways of configuration depending on which one fits better.
180
-
181
- Let's have a look at the most simple example of configuration using decorators.
182
-
183
- ```typescript
184
- import { Type, Property } from '@dipscope/type-manager';
185
-
186
- @Type()
187
- export class User
188
- {
189
- @Property(String) public name: string;
190
- @Property(String) public email: string;
191
- }
192
- ```
193
-
194
- Here we have a `User` class with `Type` and `Property` decorators assigned to it. `Type` decorator declares a type. `Property` decorator describes available properties for that type.
195
-
196
- The same configuration can be rewritten using declarative style.
197
-
198
- ```typescript
199
- import { TypeManager, PropertyName, PropertyOptions } from '@dipscope/type-manager';
200
-
201
- export class User
202
- {
203
- public name: string;
204
- public email: string;
205
- }
206
-
207
- TypeManager.configureTypeOptions(User, {
208
- propertyOptionsMap: new Map<PropertyName, PropertyOptions<any>>([
209
- ['name', { typeArgument: String }],
210
- ['email', { typeArgument: String }],
211
- ])
212
- });
213
- ```
214
-
215
- As you can see now our `User` class defined without decorators. Instead you have to call `TypeManager` configure method and provide `TypeOptions` related to `User` type.
216
-
217
- No matter what style of configuration you have chosen the next step is to call serialize methods of `TypeManager` with providing a type and data you want to process.
218
-
219
- ```typescript
220
- import { TypeManager } from '@dipscope/type-manager';
221
-
222
- const userObject = TypeManager.serialize(User, new User());
223
- const user = TypeManager.deserialize(User, userObject);
224
-
225
- user instanceof User; // True.
226
- ```
227
-
228
- Calling serialize creates a plain object and deserialize creates an instance of `User` class. During deserialize you can provide any object. It's not nesassary that object was produced by `TypeManager`. If object is an `Array` you will get array of types in return. Objects are parsed based on general type configuration defined by developer. It is also possible to stringify and parse JSON.
229
-
230
- ```typescript
231
- import { TypeManager } from '@dipscope/type-manager';
232
-
233
- const userJson = TypeManager.stringify(User, new User());
234
- const user = TypeManager.parse(User, userJson);
235
-
236
- user instanceof User; // True.
237
- ```
238
-
239
- Stringify and parse functions are wrappers over native JSON class functions. In addition they add serialize and deserialize support under the hood.
240
-
241
- Static functions are not the only way to work with a `TypeManager`. You can also work on instance based manner.
242
-
243
- ```typescript
244
- import { TypeManager } from '@dipscope/type-manager';
245
-
246
- const userManager = new TypeManager(User);
247
- const userObject = userManager.serialize(new User());
248
- const user = userManager.deserialize(userObject);
249
-
250
- user instanceof User; // True.
251
- ```
252
-
253
- At first glance, it may seems that there is no difference but creating an instance of `TypeManager` preserves a configuration state. You can work with different configurations at the same time by providing type manager options as a second optional constructor argument. If it is not required then it is better to use static methods. They are not invoking state control which results in better performance.
254
-
255
- ## Defining decorators
256
-
257
- There are few decorators which controls the main flow. This are `Type`, `Property` and `Inject` decorators. Let's go through each of them.
258
-
259
- ### Type decorator
260
-
261
- Type decorator defines a type and should be declared right before a class.
262
-
263
- ```typescript
264
- import { Type } from '@dipscope/type-manager';
265
-
266
- @Type()
267
- export class User
268
- {
269
- ...
270
- }
271
- ```
272
-
273
- This will register a new type with default type serializer assigned to it. You can define how each class should be treated by providing optional configure options as a first argument.
274
-
275
- ```typescript
276
- import { Type } from '@dipscope/type-manager';
277
-
278
- @Type({
279
- alias: 'User',
280
- serializer: new UserSerializer()
281
- })
282
- export class User
283
- {
284
- ...
285
- }
286
- ```
287
-
288
- This call defines a type alias which can be later used to resolve a type for a property at runtime. We will talk about details in the property decorator section. Also we defined custom serializer for a type which is an implementation of `Serializer` interface. This serializer will be used later to serialize and deserialize a type including all custom logic of your choice. You can read more about [creating a custom serializer](#defining-custom-serializer) in a separate section.
289
-
290
- There are more options can be provided for a type, so check `TypeOptions` definition or section with [decorator options](#defining-decorator-options) below.
291
-
292
- ### Property decorator
293
-
294
- Property decorator defines per property configuration within a type and should be declared right before a property or accessor definition.
295
-
296
- ```typescript
297
- import 'reflect-metadata';
298
- import { Type, Property } from '@dipscope/type-manager';
299
-
300
- @Type()
301
- export class User
302
- {
303
- @Property() public name: string;
304
- }
305
- ```
306
-
307
- This will register a `name` property for a `User`. Each property has a type associated with it. In our case this is a `String`. By default if no configure options are provided decorator will try to resolve a property type using [reflect-metadata](https://github.com/rbuckton/reflect-metadata). If you are not using reflect metadata then such configuration will result a property type to be `unknown` and you will get an error during serialization. For such a case you have to explicitly define a property type.
308
-
309
- ```typescript
310
- import { Type, Property } from '@dipscope/type-manager';
311
-
312
- @Type()
313
- export class User
314
- {
315
- @Property(String) public name: string;
316
- }
317
- ```
318
-
319
- Depending on your use case there are two possible ways to configure additional property options.
320
-
321
- If you are using [reflect-metadata](https://github.com/rbuckton/reflect-metadata) then provide options as a first argument.
322
-
323
- ```typescript
324
- import 'reflect-metadata';
325
- import { Type, Property } from '@dipscope/type-manager';
326
-
327
- @Type()
328
- export class User
329
- {
330
- @Property({ alias: 'username' }) public name: string;
331
- }
332
- ```
333
-
334
- If types defined explicitly then provide options as a second argument.
335
-
336
- ```typescript
337
- import { Type, Property } from '@dipscope/type-manager';
338
-
339
- @Type()
340
- export class User
341
- {
342
- @Property(String, { alias: 'username' }) public name: string;
343
- }
344
- ```
345
-
346
- This option configures an alias so `username` property will be used instead of `name` when deserializing from object. There are plenty of configure options, so check `PropertyOptions` definition or section with [decorator options](#defining-decorator-options) below. For example you can make some properties serializable only or define custom property serialization.
347
-
348
- Now let's have a look at more complex definitions with generic types. This are `Array<TType>`, `Map<TKey, TValue>` and others. To declare one of this you have to use extra argument available for `Property` decorator. Generic arguments are always passed as array to exactly see them within a source code.
349
-
350
- If you are using [reflect-metadata](https://github.com/rbuckton/reflect-metadata) then provide generics as a first argument so configure options will become the second.
351
-
352
- ```typescript
353
- import 'reflect-metadata';
354
- import { Type, Property } from '@dipscope/type-manager';
355
-
356
- @Type()
357
- export class User
358
- {
359
- @Property([String, Number], { alias: 'myMap' }) public map: Map<string, number>;
360
- }
361
- ```
362
-
363
- If types defined explicitly then provide generics as a second argument so configure options will become the third.
364
-
365
- ```typescript
366
- import { Type, Property } from '@dipscope/type-manager';
367
-
368
- @Type()
369
- export class User
370
- {
371
- @Property(Map, [String, Number], { alias: 'myMap' }) public map: Map<string, number>;
372
- }
373
- ```
374
-
375
- This is a full set of arguments available for the property. Basically when using [reflect-metadata](https://github.com/rbuckton/reflect-metadata) you have just to omit the first argument.
376
-
377
- We try to simplify declarations as much as possible so you are free to use only configure options if you want and don't ever think about `Property` decorator arguments.
378
-
379
- ```typescript
380
- import { Type, Property } from '@dipscope/type-manager';
381
-
382
- @Type()
383
- export class User
384
- {
385
- @Property({
386
- typeArgument: Map,
387
- genericArguments: [String, Number],
388
- alias: 'myMap'
389
- })
390
- public map: Map<string, number>;
391
- }
392
- ```
393
-
394
- Which syntax to use is completely on your choice. `Property` decorator is smart enough to setup everything based on usage.
395
-
396
- Now let's talk a bit about relation types. They are not differ from built in types, so if you are using [reflect-metadata](https://github.com/rbuckton/reflect-metadata) the definition can be the following.
397
-
398
- ```typescript
399
- import 'reflect-metadata';
400
- import { Type, Property } from '@dipscope/type-manager';
401
-
402
- @Type()
403
- export class UserStatus
404
- {
405
- @Property() public title: string;
406
- }
407
-
408
- @Type()
409
- export class User
410
- {
411
- @Property() public userStatus: UserStatus;
412
- }
413
- ```
414
-
415
- With array of relations you have to use generics.
416
-
417
- ```typescript
418
- import 'reflect-metadata';
419
- import { Type, Property } from '@dipscope/type-manager';
420
-
421
- @Type()
422
- export class UserStatus
423
- {
424
- @Property() public title: string;
425
- }
426
-
427
- @Type()
428
- export class User
429
- {
430
- @Property([UserStatus]) public userStatuses: UserStatus[];
431
- }
432
- ```
433
-
434
- If types defined explicitly then definition will be the following.
435
-
436
- ```typescript
437
- import { Type, Property } from '@dipscope/type-manager';
438
-
439
- @Type()
440
- export class UserStatus
441
- {
442
- @Property(String) public title: string;
443
- }
444
-
445
- @Type()
446
- export class User
447
- {
448
- @Property(UserStatus) public userStatus: UserStatus;
449
- }
450
- ```
451
-
452
- Then for array of relations it will be the following.
453
-
454
- ```typescript
455
- import { Type, Property } from '@dipscope/type-manager';
456
-
457
- @Type()
458
- export class UserStatus
459
- {
460
- @Property(String) public title: string;
461
- }
462
-
463
- @Type()
464
- export class User
465
- {
466
- @Property(Array, [UserStatus]) public userStatuses: UserStatus[];
467
- }
468
- ```
469
-
470
- If any type defines an alias - it can be used as a type resolver.
471
-
472
- ```typescript
473
- import { Type, Property } from '@dipscope/type-manager';
474
-
475
- @Type({
476
- alias: 'UserStatus'
477
- })
478
- export class UserStatus
479
- {
480
- @Property(String) public title: string;
481
- }
482
-
483
- @Type()
484
- export class User
485
- {
486
- @Property('UserStatus') public userStatus: UserStatus;
487
- }
488
- ```
489
-
490
- If you have circular reference or your type declared later an extended syntax can be used to lazily define a type.
491
-
492
- ```typescript
493
- import { Type, Property } from '@dipscope/type-manager';
494
-
495
- @Type()
496
- export class User
497
- {
498
- @Property(() => UserStatus) public userStatus: UserStatus;
499
- }
500
-
501
- @Type()
502
- export class UserStatus
503
- {
504
- @Property(() => String) public title: string;
505
- }
506
- ```
507
-
508
- One great thing to know about arguments for property type and generics is that you can pass lazy function, type directly or type alias. Which definition to use is completely on your choice and dependent from certain use cases.
509
-
510
- While property type arguments exactly match to `TypeScript` types there is a one exception for this rule. This is `Enum`. You have to provide `String` type for a string based `Enum` and `Number` type for a number based `Enum`. This is because of how `Enum` is represented after compiling it to `JavaScript`. You can read more about this [here](https://www.typescriptlang.org/docs/handbook/enums.html).
511
-
512
- If you are using [reflect-metadata](https://github.com/rbuckton/reflect-metadata) this will be done automatically so no additional steps are required from your side.
513
-
514
- ```typescript
515
- import 'reflect-metadata';
516
- import { Type, Property } from '@dipscope/type-manager';
517
-
518
- export enum UserPriorityNumeric
519
- {
520
- Low,
521
- Medium,
522
- High
523
- }
524
-
525
- export enum UserPriorityTextual
526
- {
527
- Low = 'Low',
528
- Medium = 'Medium',
529
- High = 'High'
530
- }
531
-
532
- @Type()
533
- export class User
534
- {
535
- @Property() public userPriorityNumeric: UserPriorityNumeric;
536
- @Property() public userPriorityTextual: UserPriorityTextual;
537
- }
538
- ```
539
-
540
- If types defined explicitly then definition will be the following.
541
-
542
- ```typescript
543
- import { Type, Property } from '@dipscope/type-manager';
544
-
545
- export enum UserPriorityNumeric
546
- {
547
- Low,
548
- Medium,
549
- High
550
- }
551
-
552
- export enum UserPriorityTextual
553
- {
554
- Low = 'Low',
555
- Medium = 'Medium',
556
- High = 'High'
557
- }
558
-
559
- @Type()
560
- export class User
561
- {
562
- @Property(Number) public userPriorityNumeric: UserPriorityNumeric;
563
- @Property(String) public userPriorityTextual: UserPriorityTextual;
564
- }
565
- ```
566
-
567
- One should remember this when explicitly defining types for enums.
568
-
569
- ### Inject decorator
570
-
571
- Inject decorator controls your type dependency and declared right before a constructor parameter.
572
-
573
- ```typescript
574
- import { Type, Inject } from '@dipscope/type-manager';
575
-
576
- @Type()
577
- export class User
578
- {
579
- public constructor(@Inject('name') name: string, @Inject(UserService) userService: UserService)
580
- {
581
- this.name = name;
582
-
583
- // Any action with UserService...
584
-
585
- return;
586
- }
587
- }
588
- ```
589
-
590
- It accepts two possible inputs as its argument.
591
-
592
- * String key from JSON context;
593
- * Certain type registered as injectable;
594
-
595
- When a string key is provided then a certain value will be resolved from JSON context for you when creating an instance. If any property declares the same key you will recieve deserialized value. If not then original value will be provided instead. Injecting context values is a use case of immutable types.
596
-
597
- When a certain type is provided it will be resolved from the dependency injection container. If you are going to use internal type injector then you should register injectable types as the following. By default singleton injector is used to resolve such services.
598
-
599
- ```typescript
600
- import { Type } from '@dipscope/type-manager';
601
-
602
- @Type({
603
- injectable: true
604
- })
605
- export class UserService
606
- {
607
- public property: string;
608
- }
609
- ```
610
-
611
- In most cases you will work in environment where dependency injection system is already setted up. In this case you have to implement custom `Injector` to be used instead of our default one. Besides you should follow the steps to register injectable services specified by the vendor. You can read more about [creating a custom injector](#defining-custom-injector) in a separate section.
612
-
613
- If you are using [reflect-metadata](https://github.com/rbuckton/reflect-metadata) the injection of services can be simplified.
614
-
615
- ```typescript
616
- import { Type, Inject } from '@dipscope/type-manager';
617
-
618
- @Type()
619
- export class User
620
- {
621
- public constructor(@Inject('name') name: string, userService: UserService)
622
- {
623
- this.name = name;
624
-
625
- // Any action with UserService...
626
-
627
- return;
628
- }
629
- }
630
- ```
631
-
632
- Note that now you don't have to specify injection for types explicitly. However injection of values by key from JSON context still present. It's because argument names cannot be resolved using reflection.
633
-
634
- ## Defining decorator options
635
-
636
- `Type` and `Property` decorators provide full configuration for your classes using configure options. In this section we will go through each of them.
637
-
638
- ### Alias option
639
-
640
- This option can be used both on type and property to define an alias.
641
-
642
- ```typescript
643
- import { Type, Property } from '@dipscope/type-manager';
644
-
645
- @Type({
646
- alias: 'User'
647
- })
648
- export class User
649
- {
650
- @Property(String, { alias: 'username' }) public name: string;
651
- }
652
- ```
653
-
654
- Alias defined for a class can be used later for resolving property types. Note that it should be unique within application to work properly.
655
-
656
- Alias defined for a property declares that property name differs from one specified in JSON. In our case `username` will be used instead of `name` during JSON serialization and deserialization.
657
-
658
- ### Custom data option
659
-
660
- This option can be used to provide any custom data for type or property.
661
-
662
- ```typescript
663
- import { Type, Property } from '@dipscope/type-manager';
664
-
665
- @Type({
666
- customData: { rank: 1 }
667
- })
668
- export class User
669
- {
670
- @Property(String, { customData: { order: 1 } }) public name: string;
671
- }
672
- ```
673
-
674
- This custom data later can be accessed in serializers, factories, injectors or your code and used accordingly. Read more about [defining custom data](#defining-custom-data) in a separate section.
675
-
676
- ### Default value option
677
-
678
- This option is used to define a default value when one is undefined. It can be used on type or property.
679
-
680
- ```typescript
681
- import { Type, Property } from '@dipscope/type-manager';
682
-
683
- @Type({
684
- defaultValue: () => new User()
685
- })
686
- export class User
687
- {
688
- @Property(String, { defaultValue: 'BestName' }) public name: string;
689
- }
690
- ```
691
-
692
- This will affect both serialized and deserialized default value. This will fit perfectly for most types. You can also specify serialized and deserialized default value explicitly for complex types by using two other options.
693
-
694
- ```typescript
695
- import { Type, Property } from '@dipscope/type-manager';
696
-
697
- @Type({
698
- serializedDefaultValue: () => new User(),
699
- deserializedDefaultValue: () => new User()
700
- })
701
- export class User
702
- {
703
- @Property(String, { serializedDefaultValue: 'SerializedName', deserializedDefaultValue: 'DeserializedName' }) public name: string;
704
- }
705
- ```
706
-
707
- As you can see it accepts an arrow function or a certain value. Both are valid for type and property. Using default values is turned off by default. You can enable them using `useDefaultValue` option per type and property or enable globally using `TypeManager` configure method.
708
-
709
- ### Deserializable option
710
-
711
- This option is used to enable or disable deserialization for a certain property.
712
-
713
- ```typescript
714
- import { Type, Property } from '@dipscope/type-manager';
715
-
716
- @Type()
717
- export class User
718
- {
719
- @Property(String, { deserializable: true }) public name: string;
720
- }
721
- ```
722
-
723
- By default all properties are deserializable.
724
-
725
- ### Discriminant option
726
-
727
- This option is used to define a custom discriminant for a type which is later used during serialization and deserialization of polymorphic types.
728
-
729
- ```typescript
730
- import { Type, Property } from '@dipscope/type-manager';
731
-
732
- @Type({
733
- discriminant: 'Company.Api.Entities.User'
734
- })
735
- export class User
736
- {
737
- @Property(String) public name: string;
738
- }
739
- ```
740
-
741
- You can read more about handling of polymorphic types in this [section](#configuring-usage-of-polymorphic-types).
742
-
743
- ### Discriminator option
744
-
745
- This option can be used to define a custom property which stores discriminant of polymorphic type.
746
-
747
- ```typescript
748
- import { Type, Property } from '@dipscope/type-manager';
749
-
750
- @Type({
751
- discriminator: '__typename__'
752
- })
753
- export class User
754
- {
755
- @Property(String) public name: string;
756
- }
757
- ```
758
-
759
- In common use cases discriminator should be set globally using `TypeManager` configure method. Using this option on a type level makes sense only if discriminator differs from the global one. You can read more about handling of polymorphic types in this [section](#configuring-usage-of-polymorphic-types).
760
-
761
- ### Factory option
762
-
763
- This option can be used to register a handler which should be used for constructing a type instead of default one.
764
-
765
- ```typescript
766
- import { Type, Property } from '@dipscope/type-manager';
767
-
768
- @Type({
769
- factory: new UserFactory()
770
- })
771
- export class User
772
- {
773
- @Property(String) public name: string;
774
- }
775
- ```
776
-
777
- This may be useful in cases when you want to init some special application specific properties. Read more about [defining custom factory](#defining-custom-factory) in a separate section.
778
-
779
- ### Injectable option
780
-
781
- This option is used to register a type in dependency injection container.
782
-
783
- ```typescript
784
- import { Type } from '@dipscope/type-manager';
785
-
786
- @Type({
787
- injectable: true
788
- })
789
- export class UserService
790
- {
791
- public property: string;
792
- }
793
- ```
794
-
795
- Injectable type later can be provided as a dependency.
796
-
797
- ```typescript
798
- import { Type, Property, Inject } from '@dipscope/type-manager';
799
-
800
- @Type()
801
- export class User
802
- {
803
- @Property(String) public name: string;
804
-
805
- public constructor(@Inject(UserService) userService: UserService)
806
- {
807
- // Any action with UserService...
808
-
809
- return;
810
- }
811
- }
812
- ```
813
-
814
- In most cases you will work in environment where dependency injection system is already setted up. In this case you have to implement custom `Injector` to be used instead of our default one. Besides you should follow the steps to register injectable services specified by the vendor. You can read more about [creating a custom injector](#defining-custom-injector) in a separate section.
815
-
816
- ### Injector option
817
-
818
- This option can be used to define a custom injector implementation which should be used in a type scope.
819
-
820
- ```typescript
821
- import { Type, Property } from '@dipscope/type-manager';
822
-
823
- @Type({
824
- injector: new UserInjector()
825
- })
826
- export class User
827
- {
828
- @Property(String) public name: string;
829
- }
830
- ```
831
-
832
- In most cases this is not required and the common use case is to specify injector globally instead. You can read more about [defining custom injector](#defining-custom-injector) in a separate section.
833
-
834
- ### Naming convention option
835
-
836
- This option can be used both on type and property to provide custom naming strategy.
837
-
838
- ```typescript
839
- import { Type, Property, CamelCaseNamingConvention, SnakeCaseNamingConvention } from '@dipscope/type-manager';
840
-
841
- @Type({
842
- namingConvention: new CamelCaseNamingConvention()
843
- })
844
- export class User
845
- {
846
- @Property(String, { namingConvention: new SnakeCaseNamingConvention() }) public name: string;
847
- }
848
- ```
849
-
850
- In most cases this is not required and the common use case is to specify naming strategy globally instead. You can read more about [configuring naming convention](#configuring-naming-convention) in a separate section.
851
-
852
- ### Preserve discriminator option
853
-
854
- This option defines if discriminator should be preserved in objects during serialization and deserialization.
855
-
856
- ```typescript
857
- import { Type, Property } from '@dipscope/type-manager';
858
-
859
- @Type({
860
- preserveDiscriminator: true
861
- })
862
- export class User
863
- {
864
- @Property(String) public name: string;
865
- }
866
- ```
867
-
868
- By default discriminator is not preserved and only used during deserialization of polymorphic types. You can read more about handling of polymorphic types in this [section](#configuring-usage-of-polymorphic-types).
869
-
870
- ### Preserve null option
871
-
872
- This option defines if null values should be preserved during serialization and deserialization.
873
-
874
- ```typescript
875
- import { Type, Property } from '@dipscope/type-manager';
876
-
877
- @Type({
878
- preserveNull: true
879
- })
880
- export class User
881
- {
882
- @Property(String, { preserveNull: false }) public name: string;
883
- }
884
- ```
885
-
886
- By default null values are preserved. You can set it to `false` per type, property or globally using `TypeManager` configure method. This will result in treating null values as undefined so you will get all related behaviours like setting default values.
887
-
888
- ### Reference handler option
889
-
890
- This option can be used both on type and property to specify how references to the same objects should be handled during serialization and deserialization.
891
-
892
- ```typescript
893
- import { Type, Property, DirectReferenceHandler, LeadReferenceHandler } from '@dipscope/type-manager';
894
-
895
- @Type({
896
- referenceHandler: new DirectReferenceHandler()
897
- })
898
- export class User
899
- {
900
- @Property(String, { referenceHandler: new LeadReferenceHandler() }) public name: string;
901
- }
902
- ```
903
-
904
- In most cases this is not required and the common use case is to specify reference handler globally instead. You can read more about [configuring reference handler](#configuring-reference-handler) in a separate section.
905
-
906
- ### Serializable option
907
-
908
- This option is used to enable or disable serialization for a certain property.
909
-
910
- ```typescript
911
- import { Type, Property } from '@dipscope/type-manager';
912
-
913
- @Type()
914
- export class User
915
- {
916
- @Property(String, { serializable: true }) public name: string;
917
- }
918
- ```
919
-
920
- By default all properties are serializable.
921
-
922
- ### Serializer option
923
-
924
- This option is used to define custom serializer for a type or property.
925
-
926
- ```typescript
927
- import { Type, Property } from '@dipscope/type-manager';
928
-
929
- @Type({
930
- serializer: new UserSerializer()
931
- })
932
- export class User
933
- {
934
- @Property(String, { serializer: new UserNameSerializer() }) public name: string;
935
- }
936
- ```
937
-
938
- Custom serializer should be an implementation of `Serializer` interface. You can read more about [creating a custom serializer](#defining-custom-serializer) in a separate section.
939
-
940
- ### Use default value option
941
-
942
- This option enables or disables using default value per type or property.
943
-
944
- ```typescript
945
- import { Type, Property } from '@dipscope/type-manager';
946
-
947
- @Type({
948
- useDefaultValue: true
949
- })
950
- export class User
951
- {
952
- @Property(String, { useDefaultValue: false }) public name: string;
953
- }
954
- ```
955
-
956
- Using default values is turned off by default. You can enable them globally using `TypeManager` configure method.
957
-
958
- ### Use implicit conversion option
959
-
960
- By default if declared type will not match provided during serialization or deserialization an error will be logged and result value will be undefined. This means that for example assigning `Number` to `String` will not work as `StringSerializer` expects `String`. However `Number` and other types can be converted to `String` for you when implicit conversion is enabled.
961
-
962
- ```typescript
963
- import { Type, Property } from '@dipscope/type-manager';
964
-
965
- @Type()
966
- export class User
967
- {
968
- @Property(String, { useImplicitConversion: true }) public name: string;
969
- }
970
- ```
971
-
972
- With this any value which can be converted to `String` will be converted properly. Such behaviour works for other built in serializers and supported for custom ones. By default implicit conversion is turned off. You can enable it using `useImplicitConversion` option per type and property or enable globally using `TypeManager` configure method.
973
-
974
- ## Defining configuration manually
975
-
976
- There are circumstances when decorators cannot be used or you don't want to. For example you are using a 3rd party package and cannot decorate classes from it. Another use case when you want to configure some options globally. In such scenarios you can define the complete configuration through special static configure methods.
977
-
978
- We have separate methods to configure each type manager option, so the provided examples can be simplified to avoid creating additional object. It is useful when you need to configure only one option. In our examples we are always use the main one to give you a general overview.
979
-
980
- ### Configuring global options
981
-
982
- There are several options which can be configured globally. For example let's override using of default value option so we don't have to specify it explicitly per type or property.
983
-
984
- ```typescript
985
- import { TypeManagerOptions, TypeOptionsBase } from '@dipscope/type-manager';
986
-
987
- const typeOptionsBase: TypeOptionsBase<any> = {
988
- useDefaultValue: true
989
- };
990
-
991
- const typeManagerOptions: TypeManagerOptions = {
992
- typeOptionsBase: typeOptionsBase
993
- };
994
-
995
- TypeManager.configure(typeManagerOptions);
996
- ```
997
-
998
- For the full list of available global options check `TypeOptionsBase` definition or follow the documentation as we are going to touch them while we proceed.
999
-
1000
- ### Configuring options per type
1001
-
1002
- Here is an example of declarative configuration which can be used for 3rd party or your own classes in addition to decorators.
1003
-
1004
- ```typescript
1005
- import { DateTime } from '@external-library';
1006
- import { TypeManagerOptions, TypeFn, TypeOptions, PropertyName, PropertyOptions } from '@dipscope/type-manager';
1007
-
1008
- const dateTimeOptions: TypeOptions<DateTime> = {
1009
- alias: 'DateTime',
1010
- serializer: new DateTimeSerializer()
1011
- };
1012
-
1013
- const userOptions: TypeOptions<User> = {
1014
- alias: 'User',
1015
- propertyOptionsMap: new Map<PropertyName, PropertyOptions<any>>(
1016
- ['name', { typeArgument: String, serializable: true, alias: 'username' }],
1017
- ['createdAt', { typeArgument: DateTime }]
1018
- )
1019
- };
1020
-
1021
- const typeManagerOptions: TypeManagerOptions = {
1022
- typeOptionsMap: new Map<TypeFn<any>, TypeOptions<any>>(
1023
- [DateTime, dateTimeOptions],
1024
- [User, userOptions]
1025
- )
1026
- };
1027
-
1028
- TypeManager.configure(typeManagerOptions);
1029
- ```
1030
-
1031
- There is a well defined order to how type options are applied when using configure methods on one type. One should remember this when combining and overriding options in different places.
1032
-
1033
- 1. Base type options are applied;
1034
- 2. Decorator type options are applied;
1035
- 3. Declarative type options are applied;
1036
- 4. Property type options are applied;
1037
-
1038
- Declarative configuration supports the same options as decorators. With such a configuration you can declare types like the following.
1039
-
1040
- ```typescript
1041
- export class User
1042
- {
1043
- public name: string;
1044
- public createdAt: DateTime;
1045
- }
1046
- ```
1047
-
1048
- Also if you are declaring only 3rd party classes the use case can be the following with [reflect-metadata](https://github.com/rbuckton/reflect-metadata).
1049
-
1050
- ```typescript
1051
- import 'reflect-metadata';
1052
- import { Type, Property } from '@dipscope/type-manager';
1053
-
1054
- @Type()
1055
- export class User
1056
- {
1057
- @Property() public name: string;
1058
- @Property() public createdAt: DateTime;
1059
- }
1060
- ```
1061
-
1062
- And without [reflect-metadata](https://github.com/rbuckton/reflect-metadata).
1063
-
1064
- ```typescript
1065
- import { Type, Property } from '@dipscope/type-manager';
1066
-
1067
- @Type()
1068
- export class User
1069
- {
1070
- @Property(String) public name: string;
1071
- @Property(DateTime) public createdAt: DateTime;
1072
- }
1073
- ```
1074
-
1075
- ### Configuring usage of polymorphic types
1076
-
1077
- Let's assume we are working with a shapes. To describe different types of shape we have to create an abstract class with several descendants.
1078
-
1079
- ```typescript
1080
- import { Type, Property } from '@dipscope/type-manager';
1081
-
1082
- @Type()
1083
- export abstract class Shape
1084
- {
1085
- @Property(String) public title: string;
1086
- }
1087
-
1088
- @Type()
1089
- export class Rectangle extends Shape
1090
- {
1091
- @Property(Number) public width: number;
1092
- @Property(Number) public height: number;
1093
- }
1094
-
1095
- @Type()
1096
- export class Square extends Shape
1097
- {
1098
- @Property(Number) public width: number;
1099
- }
1100
-
1101
- @Type()
1102
- export class Circle extends Shape
1103
- {
1104
- @Property(Number) public radius: number;
1105
- }
1106
- ```
1107
-
1108
- Some other class declares a `shapes` property in it.
1109
-
1110
- ```typescript
1111
- import { Type, Property } from '@dipscope/type-manager';
1112
-
1113
- @Type()
1114
- export class Plot
1115
- {
1116
- @Property(Array, [Shape]) public shapes: Shape[];
1117
- }
1118
- ```
1119
-
1120
- From the perspective of declaration everything looks ok but from the point of serialization some things may become complicated. Shapes property can store `Rectangle`, `Square` or `Circle`. Each of this classes have different properties. Here is an example of JSON.
1121
-
1122
- ```json
1123
- {
1124
- "shapes": [
1125
- {
1126
- "title": "Cool rectangle",
1127
- "width": 10,
1128
- "height": 10
1129
- },
1130
- {
1131
- "title": "Perfect square",
1132
- "width": 10
1133
- },
1134
- {
1135
- "title": "Simple circle",
1136
- "radius": 6
1137
- }
1138
- ]
1139
- }
1140
- ```
1141
-
1142
- During deserialization of this JSON to a `Plot` class we only aware that all plain objects inside an `Array` are somehow related to a `Shape` type. So any options to handle this?
1143
-
1144
- Luckily we have a `TypeManager`. When you declaring you types using decorators or declarative style it builds inheritance graph between them which can be used during serialization and deserialization.
1145
-
1146
- It uses 2 special configurable type options:
1147
-
1148
- * `Discriminator` which defines a property inside an object which should be used to define a type.
1149
- * `Discriminant` which represents a certain `Discriminator` value.
1150
-
1151
- This options have default values if you have not configured them explicitly.
1152
-
1153
- * Default value of discriminator is a `$type`. During deserialization `TypeManager` expects such property to be present inside a polymorphic object.
1154
- * Default value of discriminant is a `ClassName` which determined based on the type function.
1155
-
1156
- For proper deserialization of polymorphic types you have to provide such information inside your JSON.
1157
-
1158
- ```json
1159
- {
1160
- "shapes": [
1161
- {
1162
- "$type": "Rectangle",
1163
- "title": "Cool rectangle",
1164
- "width": 10,
1165
- "height": 10
1166
- },
1167
- {
1168
- "$type": "Square",
1169
- "title": "Perfect square",
1170
- "width": 10
1171
- },
1172
- {
1173
- "$type": "Circle",
1174
- "title": "Simple circle",
1175
- "radius": 6
1176
- }
1177
- ]
1178
- }
1179
- ```
1180
-
1181
- Now your JSON will be handled properly and you will get `Rectangle`, `Square` and `Circle` class instances in return.
1182
-
1183
- In some cases your `Discriminator` or `Discriminant` values will not match to our default ones. For example library like [Json.NET](https://www.newtonsoft.com/json) can be used on the backend side to send a response from your API. It uses `$type` property as `Discriminator` and full name of class as `Discriminant`. In such scenario our JSON may look like this.
1184
-
1185
- ```json
1186
- {
1187
- "shapes": [
1188
- {
1189
- "$type": "Company.Api.Entities.Rectangle",
1190
- "title": "Cool rectangle",
1191
- "width": 10,
1192
- "height": 10
1193
- },
1194
- {
1195
- "$type": "Company.Api.Entities.Square",
1196
- "title": "Perfect square",
1197
- "width": 10
1198
- },
1199
- {
1200
- "$type": "Company.Api.Entities.Circle",
1201
- "title": "Simple circle",
1202
- "radius": 6
1203
- }
1204
- ]
1205
- }
1206
- ```
1207
-
1208
- To change `Discriminator` globally you have to use `TypeManager` configure method.
1209
-
1210
- ```typescript
1211
- import { TypeManagerOptions, TypeOptionsBase } from '@dipscope/type-manager';
1212
-
1213
- const typeOptionsBase: TypeOptionsBase<any> = {
1214
- discriminator: '$customType'
1215
- };
1216
-
1217
- const typeManagerOptions: TypeManagerOptions = {
1218
- typeOptionsBase: typeOptionsBase
1219
- };
1220
-
1221
- TypeManager.configure(typeManagerOptions);
1222
- ```
1223
-
1224
- To change `Discriminant` you have to use per type configuration.
1225
-
1226
- ```typescript
1227
- import { TypeManagerOptions, TypeFn, TypeOptions, PropertyName, PropertyOptions } from '@dipscope/type-manager';
1228
-
1229
- const rectangleOptions: TypeOptions<Rectangle> = {
1230
- discriminant: 'Company.Api.Entities.Rectangle'
1231
- };
1232
-
1233
- const squareOptions: TypeOptions<Square> = {
1234
- discriminant: 'Company.Api.Entities.Square'
1235
- };
1236
-
1237
- const circleOptions: TypeOptions<Circle> = {
1238
- discriminant: 'Company.Api.Entities.Circle'
1239
- };
1240
-
1241
- const typeManagerOptions: TypeManagerOptions = {
1242
- typeOptionsMap: new Map<TypeFn<any>, TypeOptions<any>>(
1243
- [Rectangle, rectangleOptions],
1244
- [Square, squareOptions],
1245
- [Circle, circleOptions]
1246
- )
1247
- };
1248
-
1249
- TypeManager.configure(typeManagerOptions);
1250
- ```
1251
-
1252
- As an alternative you can change `Discriminant` as the following using decorators.
1253
-
1254
- ```typescript
1255
- import { Type, Property } from '@dipscope/type-manager';
1256
-
1257
- @Type({
1258
- discriminant: 'Company.Api.Entities.Shape'
1259
- })
1260
- export abstract class Shape
1261
- {
1262
- @Property(String) public title: string;
1263
- }
1264
-
1265
- @Type({
1266
- discriminant: 'Company.Api.Entities.Rectangle'
1267
- })
1268
- export class Rectangle extends Shape
1269
- {
1270
- @Property(Number) public width: number;
1271
- @Property(Number) public height: number;
1272
- }
1273
-
1274
- @Type({
1275
- discriminant: 'Company.Api.Entities.Square'
1276
- })
1277
- export class Square extends Shape
1278
- {
1279
- @Property(Number) public width: number;
1280
- }
1281
-
1282
- @Type({
1283
- discriminant: 'Company.Api.Entities.Circle'
1284
- })
1285
- export class Circle extends Shape
1286
- {
1287
- @Property(Number) public radius: number;
1288
- }
1289
- ```
1290
-
1291
- By default `Discriminator` is not preserved inside objects and only used during deserialization. You can change this behavior by enabling preserving of discriminator globally or per type.
1292
-
1293
- ```typescript
1294
- import { TypeManagerOptions, TypeOptionsBase } from '@dipscope/type-manager';
1295
-
1296
- const typeOptionsBase: TypeOptionsBase<any> = {
1297
- preserveDiscriminator: true
1298
- };
1299
-
1300
- const typeManagerOptions: TypeManagerOptions = {
1301
- typeOptionsBase: typeOptionsBase
1302
- };
1303
-
1304
- TypeManager.configure(typeManagerOptions);
1305
- ```
1306
-
1307
- With this option enabled discriminator will be present in output data.
1308
-
1309
- ### Configuring naming convention
1310
-
1311
- Naming convention specifies how each declared property of a type should be treated when reading it from JSON. By default names are read as is. Let's assume we have a `User` class in camel case naming convention for properties.
1312
-
1313
- ```typescript
1314
- import { Type, Property } from '@dipscope/type-manager';
1315
-
1316
- @Type()
1317
- export class User
1318
- {
1319
- @Property(String) public name: string;
1320
- @Property(Number) public loginCount: number;
1321
- @Property(DateTime) public createdAt: DateTime;
1322
- }
1323
- ```
1324
-
1325
- Our JSON should match the same naming convention to work properly.
1326
-
1327
- ```json
1328
- [
1329
- {
1330
- "name": "Dmitry",
1331
- "loginCount": 10,
1332
- "createdAt": "2021-02-22T20:15:00.000Z"
1333
- },
1334
- {
1335
- "name": "Alex",
1336
- "loginCount": 25,
1337
- "createdAt": "2021-02-22T21:15:00.000Z"
1338
- },
1339
- {
1340
- "name": "Anna",
1341
- "loginCount": 3,
1342
- "createdAt": "2021-02-22T21:15:23.000Z"
1343
- }
1344
- ]
1345
- ```
1346
-
1347
- But what to do if we don't control the JSON naming convention so it comes to us in a snake case?
1348
-
1349
- ```json
1350
- [
1351
- {
1352
- "name": "Dmitry",
1353
- "login_count": 10,
1354
- "created_at": "2021-02-22T20:15:00.000Z"
1355
- },
1356
- {
1357
- "name": "Alex",
1358
- "login_count": 25,
1359
- "created_at": "2021-02-22T21:15:00.000Z"
1360
- },
1361
- {
1362
- "name": "Anna",
1363
- "login_count": 3,
1364
- "created_at": "2021-02-22T21:15:23.000Z"
1365
- }
1366
- ]
1367
- ```
1368
-
1369
- We can still parse such a JSON by specifying an alias for each property but this will become a pain in a while.
1370
-
1371
- ```typescript
1372
- import { Type, Property } from '@dipscope/type-manager';
1373
-
1374
- @Type()
1375
- export class User
1376
- {
1377
- @Property(String) public name: string;
1378
- @Property(Number, { alias: 'login_count' }) public loginCount: number;
1379
- @Property(DateTime, { alias: 'created_at' }) public createdAt: DateTime;
1380
- }
1381
- ```
1382
-
1383
- `TypeManager` supports several naming conventions we can use to avoid dealing with aliases.
1384
-
1385
- * Camel case [camelCase];
1386
- * Flat case [flatcase];
1387
- * Flat upper case [FLATCASE];
1388
- * Kebab case [kebab-kase];
1389
- * Kebab upper case [KEBAB-CASE];
1390
- * Pascal case [PascalCase];
1391
- * Snake case [snake_case];
1392
- * Snake upper case [SNAKE_CASE];
1393
-
1394
- To set one we have to configure global options.
1395
-
1396
- ```typescript
1397
- import { TypeManagerOptions, TypeOptionsBase, SnakeCaseNamingConvention } from '@dipscope/type-manager';
1398
-
1399
- const typeOptionsBase: TypeOptionsBase<any> = {
1400
- namingConvention: new SnakeCaseNamingConvention()
1401
- };
1402
-
1403
- const typeManagerOptions: TypeManagerOptions = {
1404
- typeOptionsBase: typeOptionsBase
1405
- };
1406
-
1407
- TypeManager.configure(typeManagerOptions);
1408
- ```
1409
-
1410
- Now all property names will be converted to snake case while reading them from JSON. If you have not found suitable naming convention you can easily implement your own. Read more about [creating a custom naming convention](#defining-custom-naming-convention) in a separate section.
1411
-
1412
- ### Configuring reference handler
1413
-
1414
- Reference handler defines how references to the same objects including a circular one should be treated. We have several reference handlers: direct, lead and path. Each of them can be used globally or per type.
1415
-
1416
- * Direct reference handler preserves object references without making any special changes;
1417
- * Path reference handler preserves object references using JSONPath notation;
1418
- * Lead reference handler preserves object references excluding a circular one. When circular reference is detected it will be set to undefined;
1419
-
1420
- There is nothing better to show the difference than code. For example we have two classes which reference each other:
1421
-
1422
- ```typescript
1423
- import { Type, Property } from '@dipscope/type-manager';
1424
-
1425
- @Type()
1426
- class User
1427
- {
1428
- @Property(() => Company) public company: Company;
1429
- }
1430
-
1431
- @Type()
1432
- class Company
1433
- {
1434
- @Property(() => User) public user: User;
1435
- }
1436
- ```
1437
-
1438
- Somewhere in code you have such a logic:
1439
-
1440
- ```typescript
1441
- import { TypeManager } from '@dipscope/type-manager';
1442
-
1443
- const user = new User();
1444
- const company = new Company();
1445
-
1446
- user.company = company;
1447
- company.user = user;
1448
-
1449
- const result = TypeManager.serialize(User, user);
1450
- ```
1451
-
1452
- Here are results returned by different reference handlers:
1453
-
1454
- ```typescript
1455
- // Direct reference handler...
1456
- { company: { user: result } };
1457
-
1458
- // Path reference handler...
1459
- { company: { user: { $ref: '$' } } };
1460
-
1461
- // Lead reference handler...
1462
- { company: { user: undefined };
1463
- ```
1464
-
1465
- As you can see `DirectReferenceHandler` does not make changes to your data and completely fine until you have to convert circular reference structure to a string. `JSON.stringify` method which we are using under the hood does not support such conversions so you will encounter an error. In this case you can select another reference handler. For example `PathReferenceHandler` which produces JSON string using JSONPath format for circular references supported by many libraries. Or you can simply ignore circular reference when it should be converted to a string and use `LeadReferenceHandler`. To change default reference handler you have to use `TypeManager` configure methods.
1466
-
1467
- ```typescript
1468
- import { TypeManagerOptions, TypeOptionsBase, PathReferenceHandler } from '@dipscope/type-manager';
1469
-
1470
- const typeOptionsBase: TypeOptionsBase<any> = {
1471
- referenceHandler: new PathReferenceHandler()
1472
- };
1473
-
1474
- const typeManagerOptions: TypeManagerOptions = {
1475
- typeOptionsBase: typeOptionsBase
1476
- };
1477
-
1478
- TypeManager.configure(typeManagerOptions);
1479
- ```
1480
-
1481
- With such configuration any reference will be handled using JSONPath so you are completely free from errors during conversion to a string.
1482
-
1483
- ## Advanced usage
1484
-
1485
- Our goal is to cover as much use cases as possible without making you to write additional code but there always be an application specific case. With that in mind we allow you to customize and extend each part of our pipeline.
1486
-
1487
- ### Defining custom data
1488
-
1489
- You can attach you custom metadata to our decorators using `customData` option available on `Type` and `Property`.
1490
-
1491
- ```typescript
1492
- import { Type, Property } from '@dipscope/type-manager';
1493
-
1494
- @Type({
1495
- customData: { rank: 1 }
1496
- })
1497
- class User
1498
- {
1499
- @Property(String, { customData: { priority: 10 } }) public name: string;
1500
- }
1501
- ```
1502
-
1503
- This allows you to get it later in serializers, factories, injectors or your code and perform specific actions. Besides pipeline you can get this data in any place you want using `TypeManager`.
1504
-
1505
- ```typescript
1506
- import { TypeManager } from '@dipscope/type-manager';
1507
-
1508
- const userMetadata = TypeManager.extractTypeMetadata(User);
1509
- const customData = userMetadata.customData;
1510
-
1511
- // Do something with type custom data...
1512
-
1513
- for (const propertyMetadata of userMetadata.propertyMetadataMap.values())
1514
- {
1515
- const propertyCustomData = propertyMetadata.customData;
1516
-
1517
- // Do something with property custom data...
1518
- }
1519
- ```
1520
-
1521
- ### Defining custom serializer
1522
-
1523
- You can create your own serializer or replace built in one. First you have to implement `Serializer` interface. It declares `serialize` and `deserialize` methods. Serialize method is called during conversion of `JavaScript` object instance into a plain object. Deserialize method is called during backward conversion. Here is an example of possible definition for custom `DateTime` class.
1524
-
1525
- ```typescript
1526
- import { Serializer, TypeLike, SerializerContext } from '@dipscope/type-manager';
1527
- import { Fn } from '@app/module';
1528
-
1529
- export class DateTimeSerializer implements Serializer<DateTime>
1530
- {
1531
- public serialize(x: TypeLike<DateTime>, serializerContext: SerializerContext<DateTime>): TypeLike<string>
1532
- {
1533
- if (Fn.isUndefined(x))
1534
- {
1535
- return serializerContext.serializedDefaultValue;
1536
- }
1537
-
1538
- if (Fn.isNull(x))
1539
- {
1540
- return x;
1541
- }
1542
-
1543
- if (Fn.isDateTime(x))
1544
- {
1545
- return x.toIsoString();
1546
- }
1547
-
1548
- if (serializerContext.log.errorEnabled)
1549
- {
1550
- serializerContext.log.error(`${serializerContext.path}: cannot serialize value as date time.`, x);
1551
- }
1552
-
1553
- return undefined;
1554
- }
1555
-
1556
- public deserialize(x: TypeLike<string>, serializerContext: SerializerContext<DateTime>): TypeLike<DateTime>
1557
- {
1558
- if (Fn.isUndefined(x))
1559
- {
1560
- return serializerContext.deserializedDefaultValue;
1561
- }
1562
-
1563
- if (Fn.isNull(x))
1564
- {
1565
- return x;
1566
- }
1567
-
1568
- if (Fn.isString(x))
1569
- {
1570
- return DateTime.fromIsoString(x);
1571
- }
1572
-
1573
- if (serializerContext.log.errorEnabled)
1574
- {
1575
- serializerContext.log.error(`${serializerContext.path}: cannot deserialize value as date time.`, x);
1576
- }
1577
-
1578
- return undefined;
1579
- }
1580
- }
1581
- ```
1582
-
1583
- This example follows internal conventions and gives you a picture of how real serializer may look like. `TypeManager` does not perform any checks and just passes values directly to serializer. Thats why input values can be undefined, null or others depending from what is stored inside certain property. `TypeLike` is an internal type to declare this behaviour.
1584
-
1585
- Serializer implementation is fully responsible for return result. You can get default values, custom data and other options specified in configuration from current serializer context and react accordingly. For example you can check if implicit conversion is enabled and convert any value to the target one.
1586
-
1587
- When you are finished with definitions there are two possible ways to register a serializer. You can use decorators.
1588
-
1589
- ```typescript
1590
- import { Type, Serializer } from '@dipscope/type-manager';
1591
-
1592
- @Type({
1593
- serializer: new DateTimeSerializer()
1594
- })
1595
- export class DateTime
1596
- {
1597
- ...
1598
- }
1599
- ```
1600
-
1601
- Or declarative configuration.
1602
-
1603
- ```typescript
1604
- import { TypeManager } from '@dipscope/type-manager';
1605
-
1606
- TypeManager.configureTypeOptions(DateTime, {
1607
- alias: 'DateTime',
1608
- serializer: new DateTimeSerializer()
1609
- });
1610
- ```
1611
-
1612
- With declarative configuration it is possible to override built in serializers if it's behaviour not suitable for your use cases. Also you can register serializers for types we not yet cover.
1613
-
1614
- ### Defining custom injector
1615
-
1616
- In modern world we are always use some kind of framework to build our application. It is definitely already have a configured dependency injection container so let's configure `TypeManager` for using it instead of build in one. You have to implement `Injector` interface with only one method. Here how it may look like in `Angular`.
1617
-
1618
- ```typescript
1619
- import { Injector, TypeMetadata } from '@dipscope/type-manager';
1620
- import { Injector as AngularInjector } from '@angular/core';
1621
-
1622
- export class CustomInjector implements Injector
1623
- {
1624
- private readonly angularInjector: AngularInjector;
1625
-
1626
- public constructor(angularInjector: AngularInjector)
1627
- {
1628
- this.angularInjector = angularInjector;
1629
-
1630
- return;
1631
- }
1632
-
1633
- public get<TType>(typeMetadata: TypeMetadata<TType>): TType | undefined
1634
- {
1635
- return this.angularInjector.get(typeMetadata.typeFn);
1636
- }
1637
- }
1638
- ```
1639
-
1640
- In general you have to get framework injector or create it manually. Then call method to get and instance by type when one is requested. Implementations can differ but we hope idea is clear. When you are finished with definitions you have to register custom injector for a `TypeManager`.
1641
-
1642
- ```typescript
1643
- import { TypeManager } from '@dipscope/type-manager';
1644
- import { Injector as AngularInjector } from '@angular/core';
1645
-
1646
- const angularInjector: AngularInjector = ...; // Get framework injector in core module for example.
1647
-
1648
- TypeManager.configureTypeOptionsBase({
1649
- injector: new CustomInjector(angularInjector)
1650
- });
1651
- ```
1652
-
1653
- Now types will be resolved using framework injector.
1654
-
1655
- ### Defining custom factory
1656
-
1657
- When you want to apply additional logic to how types are constructed you can specify custom factory globally or per type. Let's say you want to init some properties based on your custom data specified for a type. You can do this by extending default `TypeFactory`.
1658
-
1659
- ```typescript
1660
- import { TypeContext, Injector, TypeFactory } from '@dipscope/type-manager';
1661
-
1662
- export class CustomTypeFactory extends TypeFactory
1663
- {
1664
- public build<TType>(typeContext: TypeContext<TType>, injector: Injector): TType
1665
- {
1666
- // Build any type.
1667
- const type = super.build(typeContext, injector) as any;
1668
-
1669
- // Resolve custom data.
1670
- const typeMetadata = typeContext.typeMetadata;
1671
- const customData = typeMetadata.customData;
1672
-
1673
- // Process custom data.
1674
- for (const propertyName in customData)
1675
- {
1676
- type[propertyName] = customData[propertyName];
1677
- }
1678
-
1679
- return type;
1680
- }
1681
- }
1682
- ```
1683
-
1684
- When you are finished with definitions there are two possible ways to register a factory. You can use decorators.
1685
-
1686
- ```typescript
1687
- import { Type, Factory } from '@dipscope/type-manager';
1688
-
1689
- @Type({
1690
- customData: { rank: 1 },
1691
- factory: new CustomTypeFactory()
1692
- })
1693
- export class User
1694
- {
1695
- ...
1696
- }
1697
- ```
1698
-
1699
- Or declarative configuration.
1700
-
1701
- ```typescript
1702
- import { TypeManager } from '@dipscope/type-manager';
1703
-
1704
- // Overriding only for user type.
1705
- TypeManager.configureTypeOptions(User, {
1706
- customData: { rank: 1 },
1707
- factory: new CustomTypeFactory()
1708
- });
1709
-
1710
- // Overriding for any type.
1711
- TypeManager.configureTypeOptionsBase({
1712
- factory: new CustomTypeFactory()
1713
- });
1714
- ```
1715
-
1716
- ### Defining custom naming convention
1717
-
1718
- To define custom naming convention you have to implement `NamingConvention` interface with only one `convert` method. Here is an example implementation of camel case naming convention.
1719
-
1720
- ```typescript
1721
- import { NamingConvention, getWords } from '@dipscope/type-manager';
1722
-
1723
- export class CamelCaseNamingConvention implements NamingConvention
1724
- {
1725
- public convert(name: string): string
1726
- {
1727
- return getWords(name).reduce(this.reduce, '');
1728
- }
1729
-
1730
- private reduce(result: string, word: string, index: number): string
1731
- {
1732
- if (word.length === 0)
1733
- {
1734
- return result;
1735
- }
1736
-
1737
- const wordLowerCased = word.toLowerCase();
1738
-
1739
- if (index === 0)
1740
- {
1741
- return wordLowerCased;
1742
- }
1743
-
1744
- return `${result}${wordLowerCased[0].toUpperCase()}${wordLowerCased.slice(1)}`;
1745
- }
1746
- }
1747
- ```
1748
-
1749
- Public `convert` method receives a property name as it declared in a class. You have to call internal `getWords` function on it which will split property name into array of the words. In the `reduce` function you can combine this words to whatever string you want. When you are finished with definitions you have to register custom naming convention for a `TypeManager`.
1750
-
1751
- ```typescript
1752
- import { TypeManager } from '@dipscope/type-manager';
1753
-
1754
- TypeManager.configureTypeOptionsBase({
1755
- namingConvention: new CamelCaseNamingConvention()
1756
- });
1757
- ```
1758
-
1759
- Now property names will be resolved using your custom naming convention.
1760
-
1761
- ## Use cases
1762
-
1763
- This section describes certain use cases to separate them from the main documentation part. We will point to a concrete place you should read to setup what is necessary.
1764
-
1765
- ### Built in serializers
1766
-
1767
- Here is a list of types with built in serializers.
1768
-
1769
- * Array;
1770
- * ArrayBuffer;
1771
- * Boolean;
1772
- * DataView;
1773
- * Date;
1774
- * Float32Array;
1775
- * Float64Array;
1776
- * Int8Array;
1777
- * Int16Array;
1778
- * Int32Array;
1779
- * Map;
1780
- * Number;
1781
- * Set;
1782
- * String;
1783
- * Uint8Array;
1784
- * Uint8ClampedArray;
1785
- * Uint16Array;
1786
- * Uint32Array;
1787
-
1788
- For these you don't have to do anything to make them work. You are free to [create a custom serializer](#defining-custom-serializer) or override built in one if it does not cover your use case.
1789
-
1790
- ### Circular object references
1791
-
1792
- We have a great support for circular references with different behaviour when they are detected. Read [configuring reference handler](#configuring-reference-handler) section for more info.
1793
-
1794
- ### Dependency injection and immutable types
1795
-
1796
- Follow the steps described in [inject decorator](#inject-decorator) section. To integrate our injection system with you yours check [defining custom injector](#defining-custom-injector) section.
1797
-
1798
- ### Different case usage in class and JSON
1799
-
1800
- If your cases differs between class and JSON. For example `camelCase` vs `snake_case`. You can setup naming convention to use during serialization and deserialization. Follow the steps described in [configuring naming convention](#configuring-naming-convention) section.
1801
-
1802
- ### Enum types
1803
-
1804
- Enum types are supported but require special handling. This is because of how enums are represented after compiling them to `JavaScript`. You can know more about how to define them in a [property decorator](#property-decorator) section. If you are interested about the `Enum` compilation details you can check the official [documentation](https://www.typescriptlang.org/docs/handbook/enums.html).
1805
-
1806
- ### Generic types
1807
-
1808
- Generic types are supported and you can define them. Read [property decorator](#property-decorator) section for more info.
1809
-
1810
- ### Integration with Angular
1811
-
1812
- With `Angular` you do not need to install [reflect-metadata](https://github.com/rbuckton/reflect-metadata) as it is already included in `core-js`. However, you still need to instruct CLI to include it in the build. This can be achieved simply by adding `import 'reflect-metadata';` to you `main.ts` file.
1813
-
1814
- To make `Angular` injector work for you a custom `Injector` needs to be implemented. Check [defining custom injector](#defining-custom-injector) section for more info.
1815
-
1816
- ### Polymorphic types
1817
-
1818
- Polymorphic types are supported. In most cases additional configuration is required. Check [configuring usage of polymorphic types](#configuring-usage-of-polymorphic-types) section for more info.
1819
-
1820
- ## Versioning
1821
-
1822
- We use [SemVer](http://semver.org/) for versioning. For the versions available, see the versions section on [NPM project page](https://www.npmjs.com/package/@dipscope/type-manager).
1823
-
1824
- See information about breaking changes, release notes and migration steps between versions in [CHANGELOG.md](https://github.com/dipscope/TypeManager.TS/blob/master/CHANGELOG.md) file.
1825
-
1826
- ## Contributing
1827
-
1828
- Please read [CONTRIBUTING.md](https://github.com/dipscope/TypeManager.TS/blob/master/CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us.
1829
-
1830
- ## Authors
1831
-
1832
- * **Dmitry Pimonov** - *Initial work* - [dpimonov](https://github.com/dpimonov)
1833
-
1834
- See also the list of [contributors](https://github.com/dipscope/TypeManager.TS/contributors) who participated in this project.
1835
-
1836
- ## Notes
1837
-
1838
- Thanks for checking this package.
1839
-
1840
- Feel free to create an issue if you find any mistakes in documentation or have any improvements in mind.
1841
-
1842
- We wish you good luck and happy coding!
1843
-
1844
- ## License
1845
-
1846
- This project is licensed under the Apache 2.0 License - see the [LICENSE.md](https://github.com/dipscope/TypeManager.TS/blob/master/LICENSE.md) file for details.
1
+ # TypeManager.TS
2
+
3
+ ![GitHub](https://img.shields.io/github/license/dipscope/TypeManager.TS) ![NPM](https://img.shields.io/npm/v/@dipscope/type-manager) ![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg)
4
+
5
+ Type manager is a parsing package for `TypeScript` which will help you to transform JSON strings or plain objects into `JavaScript` object instances. It supports [decorators](https://www.typescriptlang.org/docs/handbook/decorators.html) or declarative configuration and allows you to configure parsing of your or 3rd party classes easily.
6
+
7
+ We recommend to use our [official website](https://dipscope.com/type-manager/what-issues-it-solves) to navigate through available features. You can also use the latest documentation described below.
8
+
9
+ ## Give a star :star:
10
+
11
+ If you like or are using this project please give it a star. Thanks!
12
+
13
+ ## Table of contents
14
+
15
+ * [What issues it solves?](#what-issues-it-solves)
16
+ * [Installation](#installation)
17
+ * [How it works?](#how-it-works)
18
+ * [Defining decorators](#defining-decorators)
19
+ * [Type decorator](#type-decorator)
20
+ * [Property decorator](#property-decorator)
21
+ * [Inject decorator](#inject-decorator)
22
+ * [Defining decorator options](#defining-decorator-options)
23
+ * [Alias option](#alias-option)
24
+ * [Custom data option](#custom-data-option)
25
+ * [Default value option](#default-value-option)
26
+ * [Deserializable option](#deserializable-option)
27
+ * [Discriminant option](#discriminant-option)
28
+ * [Discriminator option](#discriminator-option)
29
+ * [Factory option](#factory-option)
30
+ * [Injectable option](#injectable-option)
31
+ * [Injector option](#injector-option)
32
+ * [Naming convention option](#naming-convention-option)
33
+ * [Preserve discriminator option](#preserve-discriminator-option)
34
+ * [Preserve null option](#preserve-null-option)
35
+ * [Reference handler option](#reference-handler-option)
36
+ * [Serializable option](#serializable-option)
37
+ * [Serializer option](#serializer-option)
38
+ * [Use default value option](#use-default-value-option)
39
+ * [Use implicit conversion option](#use-implicit-conversion-option)
40
+ * [Defining configuration manually](#defining-configuration-manually)
41
+ * [Configuring global options](#configuring-global-options)
42
+ * [Configuring options per type](#configuring-options-per-type)
43
+ * [Configuring usage of polymorphic types](#configuring-usage-of-polymorphic-types)
44
+ * [Configuring naming convention](#configuring-naming-convention)
45
+ * [Configuring reference handler](#configuring-reference-handler)
46
+ * [Advanced usage](#advanced-usage)
47
+ * [Defining custom data](#defining-custom-data)
48
+ * [Defining custom serializer](#defining-custom-serializer)
49
+ * [Defining custom injector](#defining-custom-injector)
50
+ * [Defining custom factory](#defining-custom-factory)
51
+ * [Defining custom naming convention](#defining-custom-naming-convention)
52
+ * [Use cases](#use-cases)
53
+ * [Built in serializers](#built-in-serializers)
54
+ * [Circular object references](#circular-object-references)
55
+ * [Dependency injection and immutable types](#dependency-injection-and-immutable-types)
56
+ * [Different case usage in class and JSON](#different-case-usage-in-class-and-json)
57
+ * [Enum types](#enum-types)
58
+ * [Generic types](#generic-types)
59
+ * [Integration with Angular](#integration-with-angular)
60
+ * [Polymorphic types](#polymorphic-types)
61
+ * [Versioning](#versioning)
62
+ * [Contributing](#contributing)
63
+ * [Authors](#authors)
64
+ * [Notes](#notes)
65
+ * [License](#license)
66
+
67
+ ## What issues it solves?
68
+
69
+ In `JavaScript` there are two types of objects:
70
+
71
+ * Plain objects which are created using `{}` notation;
72
+ * Constructor based objects which are created using `new Class()` notation.
73
+
74
+ Sometimes we want to transform plain objects to the classes we have. Let's assume we are loading a users JSON data from our backend API or the other datasource:
75
+
76
+ ```json
77
+ [
78
+ {
79
+ "id": 1,
80
+ "name": "Dmitry",
81
+ "deletedAt": "2021-02-22T20:15:00.000Z"
82
+ },
83
+ {
84
+ "id": 2,
85
+ "name": "Alex",
86
+ "deletedAt": null
87
+ },
88
+ {
89
+ "id": 3,
90
+ "name": "Anna",
91
+ "deletedAt": null
92
+ }
93
+ ]
94
+ ```
95
+
96
+ We have a `User` class:
97
+
98
+ ```typescript
99
+ export class User
100
+ {
101
+ public id: number;
102
+ public name: string;
103
+ public deletedAt: Date;
104
+
105
+ public constructor(id: number, name: string)
106
+ {
107
+ this.id = id;
108
+ this.name = name;
109
+
110
+ return;
111
+ }
112
+
113
+ public isDeleted(): boolean
114
+ {
115
+ return this.deletedAt !== null;
116
+ }
117
+ }
118
+ ```
119
+
120
+ Somewhere in code we are checking if user is deleted before performing some action.
121
+
122
+ ```typescript
123
+ const users: User[] = JSON.parse(usersJson);
124
+
125
+ for (const user of users)
126
+ {
127
+ if (user.isDeleted())
128
+ {
129
+ // Do some action...
130
+ }
131
+ }
132
+ ```
133
+
134
+ Do you see the problem in this piece of code?
135
+
136
+ `JSON.parse` function returns plain objects and we actually lied to compiler when said that it is a `User` class array. In this code we can successfully use `user.id` or `user.name`. However we cannot use `user.isDeleted()` because user is not an instance of a `User` class.
137
+
138
+ So what to do? How to get `User` array from our JSON?
139
+
140
+ Solution is to create new instances of `User` class from plain objects returned by `JSON.parse` function. But things may go wrong once you have a more complex object hierarchy. Besides `deletedAt` property is represented as `String` in JSON but `User` class declares it as a `Date` so we also have to perform appropriate conversion when assigning this property.
141
+
142
+ There exists much more simple way. Let's use our `TypeManager` for getting instances of `User` class from JSON:
143
+
144
+ ```typescript
145
+ import { TypeManager } from '@dipscope/type-manager';
146
+
147
+ const users: User[] = TypeManager.parse(User, usersJson);
148
+
149
+ for (const user of users)
150
+ {
151
+ if (user.isDeleted())
152
+ {
153
+ // Do some action...
154
+ }
155
+ }
156
+ ```
157
+
158
+ Now we can use all power provided by `JavaScript` class instances.
159
+
160
+ Furthermore `TypeManager.TS` provides you:
161
+
162
+ * Reflection abilities at runtime;
163
+ * Support for generic types;
164
+ * Handling of cyclic object references and different ways of serialization when they appear;
165
+ * Ability to configure serialization of 3rd party classes;
166
+ * Support for polymorphic types;
167
+ * Great alternative for similar packages like [class-transformer](https://github.com/typestack/class-transformer), [TypedJSON](https://github.com/JohnWeisz/TypedJSON) and [jackson-js](https://github.com/pichillilorenzo/jackson-js);
168
+
169
+ Want to know more? Let's dive into the details.
170
+
171
+ ## Installation
172
+
173
+ `TypeManager.TS` is available from NPM, both for browser (e.g. using webpack) and NodeJS:
174
+
175
+ ```
176
+ npm i @dipscope/type-manager
177
+ ```
178
+
179
+ TypeScript needs to run with the `experimentalDecorators` and `emitDecoratorMetadata` options enabled when using decorator annotations. So make sure you have properly configured your `tsconfig.json` file.
180
+
181
+ _If you want additional type-safety and reduced syntax you may wish to install [reflect-metadata](https://github.com/rbuckton/reflect-metadata). This step is on your choice and fully optional. When installed it must be available globally to work. This can usually be done with `import 'reflect-metadata';` in your main index file._
182
+
183
+ ## How it works?
184
+
185
+ It defines configuration for each object which you are going to serialize or deserialize and uses this configuration to process data of your choice. There are two possible ways to define a configuration:
186
+
187
+ * Using decorator annotations;
188
+ * Using declarative style;
189
+
190
+ The first one is the easiest and can be used for any class you control. If you want to configure serialization of 3rd party classes, global options or you don't like decorators it is better to go with the second. There are no restrictions to use one or another. You can combine two ways of configuration depending on which one fits better.
191
+
192
+ Let's have a look at the most simple example of configuration using decorators.
193
+
194
+ ```typescript
195
+ import { Type, Property } from '@dipscope/type-manager';
196
+
197
+ @Type()
198
+ export class User
199
+ {
200
+ @Property(String) public name: string;
201
+ @Property(String) public email: string;
202
+ }
203
+ ```
204
+
205
+ Here we have a `User` class with `Type` and `Property` decorators assigned to it. `Type` decorator declares a type. `Property` decorator describes available properties for that type.
206
+
207
+ The same configuration can be rewritten using declarative style.
208
+
209
+ ```typescript
210
+ import { TypeManager, PropertyName, PropertyOptions } from '@dipscope/type-manager';
211
+
212
+ export class User
213
+ {
214
+ public name: string;
215
+ public email: string;
216
+ }
217
+
218
+ TypeManager.configureTypeOptions(User, {
219
+ propertyOptionsMap: new Map<PropertyName, PropertyOptions<any>>([
220
+ ['name', { typeArgument: String }],
221
+ ['email', { typeArgument: String }],
222
+ ])
223
+ });
224
+ ```
225
+
226
+ As you can see now our `User` class defined without decorators. Instead you have to call `TypeManager` configure method and provide `TypeOptions` related to `User` type.
227
+
228
+ No matter what style of configuration you have chosen the next step is to call serialize methods of `TypeManager` with providing a type and data you want to process.
229
+
230
+ ```typescript
231
+ import { TypeManager } from '@dipscope/type-manager';
232
+
233
+ const userObject = TypeManager.serialize(User, new User());
234
+ const user = TypeManager.deserialize(User, userObject);
235
+
236
+ user instanceof User; // True.
237
+ ```
238
+
239
+ Calling serialize creates a plain object and deserialize creates an instance of `User` class. During deserialize you can provide any object. It's not nesassary that object was produced by `TypeManager`. If object is an `Array` you will get array of types in return. Objects are parsed based on general type configuration defined by developer. It is also possible to stringify and parse JSON.
240
+
241
+ ```typescript
242
+ import { TypeManager } from '@dipscope/type-manager';
243
+
244
+ const userJson = TypeManager.stringify(User, new User());
245
+ const user = TypeManager.parse(User, userJson);
246
+
247
+ user instanceof User; // True.
248
+ ```
249
+
250
+ Stringify and parse functions are wrappers over native JSON class functions. In addition they add serialize and deserialize support under the hood.
251
+
252
+ Static functions are not the only way to work with a `TypeManager`. You can also work on instance based manner.
253
+
254
+ ```typescript
255
+ import { TypeManager } from '@dipscope/type-manager';
256
+
257
+ const userManager = new TypeManager(User);
258
+ const userObject = userManager.serialize(new User());
259
+ const user = userManager.deserialize(userObject);
260
+
261
+ user instanceof User; // True.
262
+ ```
263
+
264
+ At first glance, it may seems that there is no difference but creating an instance of `TypeManager` preserves a configuration state. You can work with different configurations at the same time by providing type manager options as a second optional constructor argument. If it is not required then it is better to use static methods. They are not invoking state control which results in better performance.
265
+
266
+ ## Defining decorators
267
+
268
+ There are few decorators which controls the main flow. This are `Type`, `Property` and `Inject` decorators. Let's go through each of them.
269
+
270
+ ### Type decorator
271
+
272
+ Type decorator defines a type and should be declared right before a class.
273
+
274
+ ```typescript
275
+ import { Type } from '@dipscope/type-manager';
276
+
277
+ @Type()
278
+ export class User
279
+ {
280
+ ...
281
+ }
282
+ ```
283
+
284
+ This will register a new type with default type serializer assigned to it. You can define how each class should be treated by providing optional configure options as a first argument.
285
+
286
+ ```typescript
287
+ import { Type } from '@dipscope/type-manager';
288
+
289
+ @Type({
290
+ alias: 'User',
291
+ serializer: new UserSerializer()
292
+ })
293
+ export class User
294
+ {
295
+ ...
296
+ }
297
+ ```
298
+
299
+ This call defines a type alias which can be later used to resolve a type for a property at runtime. We will talk about details in the property decorator section. Also we defined custom serializer for a type which is an implementation of `Serializer` interface. This serializer will be used later to serialize and deserialize a type including all custom logic of your choice. You can read more about [creating a custom serializer](#defining-custom-serializer) in a separate section.
300
+
301
+ There are more options can be provided for a type, so check `TypeOptions` definition or section with [decorator options](#defining-decorator-options) below.
302
+
303
+ ### Property decorator
304
+
305
+ Property decorator defines per property configuration within a type and should be declared right before a property or accessor definition.
306
+
307
+ ```typescript
308
+ import 'reflect-metadata';
309
+ import { Type, Property } from '@dipscope/type-manager';
310
+
311
+ @Type()
312
+ export class User
313
+ {
314
+ @Property() public name: string;
315
+ }
316
+ ```
317
+
318
+ This will register a `name` property for a `User`. Each property has a type associated with it. In our case this is a `String`. By default if no configure options are provided decorator will try to resolve a property type using [reflect-metadata](https://github.com/rbuckton/reflect-metadata). If you are not using reflect metadata then such configuration will result a property type to be `unknown` and you will get an error during serialization. For such a case you have to explicitly define a property type.
319
+
320
+ ```typescript
321
+ import { Type, Property } from '@dipscope/type-manager';
322
+
323
+ @Type()
324
+ export class User
325
+ {
326
+ @Property(String) public name: string;
327
+ }
328
+ ```
329
+
330
+ Depending on your use case there are two possible ways to configure additional property options.
331
+
332
+ If you are using [reflect-metadata](https://github.com/rbuckton/reflect-metadata) then provide options as a first argument.
333
+
334
+ ```typescript
335
+ import 'reflect-metadata';
336
+ import { Type, Property } from '@dipscope/type-manager';
337
+
338
+ @Type()
339
+ export class User
340
+ {
341
+ @Property({ alias: 'username' }) public name: string;
342
+ }
343
+ ```
344
+
345
+ If types defined explicitly then provide options as a second argument.
346
+
347
+ ```typescript
348
+ import { Type, Property } from '@dipscope/type-manager';
349
+
350
+ @Type()
351
+ export class User
352
+ {
353
+ @Property(String, { alias: 'username' }) public name: string;
354
+ }
355
+ ```
356
+
357
+ This option configures an alias so `username` property will be used instead of `name` when deserializing from object. There are plenty of configure options, so check `PropertyOptions` definition or section with [decorator options](#defining-decorator-options) below. For example you can make some properties serializable only or define custom property serialization.
358
+
359
+ Now let's have a look at more complex definitions with generic types. This are `Array<TType>`, `Map<TKey, TValue>` and others. To declare one of this you have to use extra argument available for `Property` decorator. Generic arguments are always passed as array to exactly see them within a source code.
360
+
361
+ If you are using [reflect-metadata](https://github.com/rbuckton/reflect-metadata) then provide generics as a first argument so configure options will become the second.
362
+
363
+ ```typescript
364
+ import 'reflect-metadata';
365
+ import { Type, Property } from '@dipscope/type-manager';
366
+
367
+ @Type()
368
+ export class User
369
+ {
370
+ @Property([String, Number], { alias: 'myMap' }) public map: Map<string, number>;
371
+ }
372
+ ```
373
+
374
+ If types defined explicitly then provide generics as a second argument so configure options will become the third.
375
+
376
+ ```typescript
377
+ import { Type, Property } from '@dipscope/type-manager';
378
+
379
+ @Type()
380
+ export class User
381
+ {
382
+ @Property(Map, [String, Number], { alias: 'myMap' }) public map: Map<string, number>;
383
+ }
384
+ ```
385
+
386
+ This is a full set of arguments available for the property. Basically when using [reflect-metadata](https://github.com/rbuckton/reflect-metadata) you have just to omit the first argument.
387
+
388
+ We try to simplify declarations as much as possible so you are free to use only configure options if you want and don't ever think about `Property` decorator arguments.
389
+
390
+ ```typescript
391
+ import { Type, Property } from '@dipscope/type-manager';
392
+
393
+ @Type()
394
+ export class User
395
+ {
396
+ @Property({
397
+ typeArgument: Map,
398
+ genericArguments: [String, Number],
399
+ alias: 'myMap'
400
+ })
401
+ public map: Map<string, number>;
402
+ }
403
+ ```
404
+
405
+ Which syntax to use is completely on your choice. `Property` decorator is smart enough to setup everything based on usage.
406
+
407
+ Now let's talk a bit about relation types. They are not differ from built in types, so if you are using [reflect-metadata](https://github.com/rbuckton/reflect-metadata) the definition can be the following.
408
+
409
+ ```typescript
410
+ import 'reflect-metadata';
411
+ import { Type, Property } from '@dipscope/type-manager';
412
+
413
+ @Type()
414
+ export class UserStatus
415
+ {
416
+ @Property() public title: string;
417
+ }
418
+
419
+ @Type()
420
+ export class User
421
+ {
422
+ @Property() public userStatus: UserStatus;
423
+ }
424
+ ```
425
+
426
+ With array of relations you have to use generics.
427
+
428
+ ```typescript
429
+ import 'reflect-metadata';
430
+ import { Type, Property } from '@dipscope/type-manager';
431
+
432
+ @Type()
433
+ export class UserStatus
434
+ {
435
+ @Property() public title: string;
436
+ }
437
+
438
+ @Type()
439
+ export class User
440
+ {
441
+ @Property([UserStatus]) public userStatuses: UserStatus[];
442
+ }
443
+ ```
444
+
445
+ If types defined explicitly then definition will be the following.
446
+
447
+ ```typescript
448
+ import { Type, Property } from '@dipscope/type-manager';
449
+
450
+ @Type()
451
+ export class UserStatus
452
+ {
453
+ @Property(String) public title: string;
454
+ }
455
+
456
+ @Type()
457
+ export class User
458
+ {
459
+ @Property(UserStatus) public userStatus: UserStatus;
460
+ }
461
+ ```
462
+
463
+ Then for array of relations it will be the following.
464
+
465
+ ```typescript
466
+ import { Type, Property } from '@dipscope/type-manager';
467
+
468
+ @Type()
469
+ export class UserStatus
470
+ {
471
+ @Property(String) public title: string;
472
+ }
473
+
474
+ @Type()
475
+ export class User
476
+ {
477
+ @Property(Array, [UserStatus]) public userStatuses: UserStatus[];
478
+ }
479
+ ```
480
+
481
+ If any type defines an alias - it can be used as a type resolver.
482
+
483
+ ```typescript
484
+ import { Type, Property } from '@dipscope/type-manager';
485
+
486
+ @Type({
487
+ alias: 'UserStatus'
488
+ })
489
+ export class UserStatus
490
+ {
491
+ @Property(String) public title: string;
492
+ }
493
+
494
+ @Type()
495
+ export class User
496
+ {
497
+ @Property('UserStatus') public userStatus: UserStatus;
498
+ }
499
+ ```
500
+
501
+ If you have circular reference or your type declared later an extended syntax can be used to lazily define a type.
502
+
503
+ ```typescript
504
+ import { Type, Property } from '@dipscope/type-manager';
505
+
506
+ @Type()
507
+ export class User
508
+ {
509
+ @Property(() => UserStatus) public userStatus: UserStatus;
510
+ }
511
+
512
+ @Type()
513
+ export class UserStatus
514
+ {
515
+ @Property(() => String) public title: string;
516
+ }
517
+ ```
518
+
519
+ One great thing to know about arguments for property type and generics is that you can pass lazy function, type directly or type alias. Which definition to use is completely on your choice and dependent from certain use cases.
520
+
521
+ While property type arguments exactly match to `TypeScript` types there is a one exception for this rule. This is `Enum`. You have to provide `String` type for a string based `Enum` and `Number` type for a number based `Enum`. This is because of how `Enum` is represented after compiling it to `JavaScript`. You can read more about this [here](https://www.typescriptlang.org/docs/handbook/enums.html).
522
+
523
+ If you are using [reflect-metadata](https://github.com/rbuckton/reflect-metadata) this will be done automatically so no additional steps are required from your side.
524
+
525
+ ```typescript
526
+ import 'reflect-metadata';
527
+ import { Type, Property } from '@dipscope/type-manager';
528
+
529
+ export enum UserPriorityNumeric
530
+ {
531
+ Low,
532
+ Medium,
533
+ High
534
+ }
535
+
536
+ export enum UserPriorityTextual
537
+ {
538
+ Low = 'Low',
539
+ Medium = 'Medium',
540
+ High = 'High'
541
+ }
542
+
543
+ @Type()
544
+ export class User
545
+ {
546
+ @Property() public userPriorityNumeric: UserPriorityNumeric;
547
+ @Property() public userPriorityTextual: UserPriorityTextual;
548
+ }
549
+ ```
550
+
551
+ If types defined explicitly then definition will be the following.
552
+
553
+ ```typescript
554
+ import { Type, Property } from '@dipscope/type-manager';
555
+
556
+ export enum UserPriorityNumeric
557
+ {
558
+ Low,
559
+ Medium,
560
+ High
561
+ }
562
+
563
+ export enum UserPriorityTextual
564
+ {
565
+ Low = 'Low',
566
+ Medium = 'Medium',
567
+ High = 'High'
568
+ }
569
+
570
+ @Type()
571
+ export class User
572
+ {
573
+ @Property(Number) public userPriorityNumeric: UserPriorityNumeric;
574
+ @Property(String) public userPriorityTextual: UserPriorityTextual;
575
+ }
576
+ ```
577
+
578
+ One should remember this when explicitly defining types for enums.
579
+
580
+ ### Inject decorator
581
+
582
+ Inject decorator controls your type dependency and declared right before a constructor parameter.
583
+
584
+ ```typescript
585
+ import { Type, Inject } from '@dipscope/type-manager';
586
+
587
+ @Type()
588
+ export class User
589
+ {
590
+ public constructor(@Inject('name') name: string, @Inject(UserService) userService: UserService)
591
+ {
592
+ this.name = name;
593
+
594
+ // Any action with UserService...
595
+
596
+ return;
597
+ }
598
+ }
599
+ ```
600
+
601
+ It accepts two possible inputs as its argument.
602
+
603
+ * String key from JSON context;
604
+ * Certain type registered as injectable;
605
+
606
+ When a string key is provided then a certain value will be resolved from JSON context for you when creating an instance. If any property declares the same key you will recieve deserialized value. If not then original value will be provided instead. Injecting context values is a use case of immutable types.
607
+
608
+ When a certain type is provided it will be resolved from the dependency injection container. If you are going to use internal type injector then you should register injectable types as the following. By default singleton injector is used to resolve such services.
609
+
610
+ ```typescript
611
+ import { Type } from '@dipscope/type-manager';
612
+
613
+ @Type({
614
+ injectable: true
615
+ })
616
+ export class UserService
617
+ {
618
+ public property: string;
619
+ }
620
+ ```
621
+
622
+ In most cases you will work in environment where dependency injection system is already setted up. In this case you have to implement custom `Injector` to be used instead of our default one. Besides you should follow the steps to register injectable services specified by the vendor. You can read more about [creating a custom injector](#defining-custom-injector) in a separate section.
623
+
624
+ If you are using [reflect-metadata](https://github.com/rbuckton/reflect-metadata) the injection of services can be simplified.
625
+
626
+ ```typescript
627
+ import { Type, Inject } from '@dipscope/type-manager';
628
+
629
+ @Type()
630
+ export class User
631
+ {
632
+ public constructor(@Inject('name') name: string, userService: UserService)
633
+ {
634
+ this.name = name;
635
+
636
+ // Any action with UserService...
637
+
638
+ return;
639
+ }
640
+ }
641
+ ```
642
+
643
+ Note that now you don't have to specify injection for types explicitly. However injection of values by key from JSON context still present. It's because argument names cannot be resolved using reflection.
644
+
645
+ ## Defining decorator options
646
+
647
+ `Type` and `Property` decorators provide full configuration for your classes using configure options. In this section we will go through each of them.
648
+
649
+ ### Alias option
650
+
651
+ This option can be used both on type and property to define an alias.
652
+
653
+ ```typescript
654
+ import { Type, Property } from '@dipscope/type-manager';
655
+
656
+ @Type({
657
+ alias: 'User'
658
+ })
659
+ export class User
660
+ {
661
+ @Property(String, { alias: 'username' }) public name: string;
662
+ }
663
+ ```
664
+
665
+ Alias defined for a class can be used later for resolving property types. Note that it should be unique within application to work properly.
666
+
667
+ Alias defined for a property declares that property name differs from one specified in JSON. In our case `username` will be used instead of `name` during JSON serialization and deserialization.
668
+
669
+ ### Custom data option
670
+
671
+ This option can be used to provide any custom data for type or property.
672
+
673
+ ```typescript
674
+ import { Type, Property } from '@dipscope/type-manager';
675
+
676
+ @Type({
677
+ customData: { rank: 1 }
678
+ })
679
+ export class User
680
+ {
681
+ @Property(String, { customData: { order: 1 } }) public name: string;
682
+ }
683
+ ```
684
+
685
+ This custom data later can be accessed in serializers, factories, injectors or your code and used accordingly. Read more about [defining custom data](#defining-custom-data) in a separate section.
686
+
687
+ ### Default value option
688
+
689
+ This option is used to define a default value when one is undefined. It can be used on type or property.
690
+
691
+ ```typescript
692
+ import { Type, Property } from '@dipscope/type-manager';
693
+
694
+ @Type({
695
+ defaultValue: () => new User()
696
+ })
697
+ export class User
698
+ {
699
+ @Property(String, { defaultValue: 'BestName' }) public name: string;
700
+ }
701
+ ```
702
+
703
+ This will affect both serialized and deserialized default value. This will fit perfectly for most types. You can also specify serialized and deserialized default value explicitly for complex types by using two other options.
704
+
705
+ ```typescript
706
+ import { Type, Property } from '@dipscope/type-manager';
707
+
708
+ @Type({
709
+ serializedDefaultValue: () => new User(),
710
+ deserializedDefaultValue: () => new User()
711
+ })
712
+ export class User
713
+ {
714
+ @Property(String, { serializedDefaultValue: 'SerializedName', deserializedDefaultValue: 'DeserializedName' }) public name: string;
715
+ }
716
+ ```
717
+
718
+ As you can see it accepts an arrow function or a certain value. Both are valid for type and property. Using default values is turned off by default. You can enable them using `useDefaultValue` option per type and property or enable globally using `TypeManager` configure method.
719
+
720
+ ### Deserializable option
721
+
722
+ This option is used to enable or disable deserialization for a certain property.
723
+
724
+ ```typescript
725
+ import { Type, Property } from '@dipscope/type-manager';
726
+
727
+ @Type()
728
+ export class User
729
+ {
730
+ @Property(String, { deserializable: true }) public name: string;
731
+ }
732
+ ```
733
+
734
+ By default all properties are deserializable.
735
+
736
+ ### Discriminant option
737
+
738
+ This option is used to define a custom discriminant for a type which is later used during serialization and deserialization of polymorphic types.
739
+
740
+ ```typescript
741
+ import { Type, Property } from '@dipscope/type-manager';
742
+
743
+ @Type({
744
+ discriminant: 'Company.Api.Entities.User'
745
+ })
746
+ export class User
747
+ {
748
+ @Property(String) public name: string;
749
+ }
750
+ ```
751
+
752
+ You can read more about handling of polymorphic types in this [section](#configuring-usage-of-polymorphic-types).
753
+
754
+ ### Discriminator option
755
+
756
+ This option can be used to define a custom property which stores discriminant of polymorphic type.
757
+
758
+ ```typescript
759
+ import { Type, Property } from '@dipscope/type-manager';
760
+
761
+ @Type({
762
+ discriminator: '__typename__'
763
+ })
764
+ export class User
765
+ {
766
+ @Property(String) public name: string;
767
+ }
768
+ ```
769
+
770
+ In common use cases discriminator should be set globally using `TypeManager` configure method. Using this option on a type level makes sense only if discriminator differs from the global one. You can read more about handling of polymorphic types in this [section](#configuring-usage-of-polymorphic-types).
771
+
772
+ ### Factory option
773
+
774
+ This option can be used to register a handler which should be used for constructing a type instead of default one.
775
+
776
+ ```typescript
777
+ import { Type, Property } from '@dipscope/type-manager';
778
+
779
+ @Type({
780
+ factory: new UserFactory()
781
+ })
782
+ export class User
783
+ {
784
+ @Property(String) public name: string;
785
+ }
786
+ ```
787
+
788
+ This may be useful in cases when you want to init some special application specific properties. Read more about [defining custom factory](#defining-custom-factory) in a separate section.
789
+
790
+ ### Injectable option
791
+
792
+ This option is used to register a type in dependency injection container.
793
+
794
+ ```typescript
795
+ import { Type } from '@dipscope/type-manager';
796
+
797
+ @Type({
798
+ injectable: true
799
+ })
800
+ export class UserService
801
+ {
802
+ public property: string;
803
+ }
804
+ ```
805
+
806
+ Injectable type later can be provided as a dependency.
807
+
808
+ ```typescript
809
+ import { Type, Property, Inject } from '@dipscope/type-manager';
810
+
811
+ @Type()
812
+ export class User
813
+ {
814
+ @Property(String) public name: string;
815
+
816
+ public constructor(@Inject(UserService) userService: UserService)
817
+ {
818
+ // Any action with UserService...
819
+
820
+ return;
821
+ }
822
+ }
823
+ ```
824
+
825
+ In most cases you will work in environment where dependency injection system is already setted up. In this case you have to implement custom `Injector` to be used instead of our default one. Besides you should follow the steps to register injectable services specified by the vendor. You can read more about [creating a custom injector](#defining-custom-injector) in a separate section.
826
+
827
+ ### Injector option
828
+
829
+ This option can be used to define a custom injector implementation which should be used in a type scope.
830
+
831
+ ```typescript
832
+ import { Type, Property } from '@dipscope/type-manager';
833
+
834
+ @Type({
835
+ injector: new UserInjector()
836
+ })
837
+ export class User
838
+ {
839
+ @Property(String) public name: string;
840
+ }
841
+ ```
842
+
843
+ In most cases this is not required and the common use case is to specify injector globally instead. You can read more about [defining custom injector](#defining-custom-injector) in a separate section.
844
+
845
+ ### Naming convention option
846
+
847
+ This option can be used both on type and property to provide custom naming strategy.
848
+
849
+ ```typescript
850
+ import { Type, Property, CamelCaseNamingConvention, SnakeCaseNamingConvention } from '@dipscope/type-manager';
851
+
852
+ @Type({
853
+ namingConvention: new CamelCaseNamingConvention()
854
+ })
855
+ export class User
856
+ {
857
+ @Property(String, { namingConvention: new SnakeCaseNamingConvention() }) public name: string;
858
+ }
859
+ ```
860
+
861
+ In most cases this is not required and the common use case is to specify naming strategy globally instead. You can read more about [configuring naming convention](#configuring-naming-convention) in a separate section.
862
+
863
+ ### Preserve discriminator option
864
+
865
+ This option defines if discriminator should be preserved in objects during serialization and deserialization.
866
+
867
+ ```typescript
868
+ import { Type, Property } from '@dipscope/type-manager';
869
+
870
+ @Type({
871
+ preserveDiscriminator: true
872
+ })
873
+ export class User
874
+ {
875
+ @Property(String) public name: string;
876
+ }
877
+ ```
878
+
879
+ By default discriminator is not preserved and only used during deserialization of polymorphic types. You can read more about handling of polymorphic types in this [section](#configuring-usage-of-polymorphic-types).
880
+
881
+ ### Preserve null option
882
+
883
+ This option defines if null values should be preserved during serialization and deserialization.
884
+
885
+ ```typescript
886
+ import { Type, Property } from '@dipscope/type-manager';
887
+
888
+ @Type({
889
+ preserveNull: true
890
+ })
891
+ export class User
892
+ {
893
+ @Property(String, { preserveNull: false }) public name: string;
894
+ }
895
+ ```
896
+
897
+ By default null values are preserved. You can set it to `false` per type, property or globally using `TypeManager` configure method. This will result in treating null values as undefined so you will get all related behaviours like setting default values.
898
+
899
+ ### Reference handler option
900
+
901
+ This option can be used both on type and property to specify how references to the same objects should be handled during serialization and deserialization.
902
+
903
+ ```typescript
904
+ import { Type, Property, DirectReferenceHandler, LeadReferenceHandler } from '@dipscope/type-manager';
905
+
906
+ @Type({
907
+ referenceHandler: new DirectReferenceHandler()
908
+ })
909
+ export class User
910
+ {
911
+ @Property(String, { referenceHandler: new LeadReferenceHandler() }) public name: string;
912
+ }
913
+ ```
914
+
915
+ In most cases this is not required and the common use case is to specify reference handler globally instead. You can read more about [configuring reference handler](#configuring-reference-handler) in a separate section.
916
+
917
+ ### Serializable option
918
+
919
+ This option is used to enable or disable serialization for a certain property.
920
+
921
+ ```typescript
922
+ import { Type, Property } from '@dipscope/type-manager';
923
+
924
+ @Type()
925
+ export class User
926
+ {
927
+ @Property(String, { serializable: true }) public name: string;
928
+ }
929
+ ```
930
+
931
+ By default all properties are serializable.
932
+
933
+ ### Serializer option
934
+
935
+ This option is used to define custom serializer for a type or property.
936
+
937
+ ```typescript
938
+ import { Type, Property } from '@dipscope/type-manager';
939
+
940
+ @Type({
941
+ serializer: new UserSerializer()
942
+ })
943
+ export class User
944
+ {
945
+ @Property(String, { serializer: new UserNameSerializer() }) public name: string;
946
+ }
947
+ ```
948
+
949
+ Custom serializer should be an implementation of `Serializer` interface. You can read more about [creating a custom serializer](#defining-custom-serializer) in a separate section.
950
+
951
+ ### Use default value option
952
+
953
+ This option enables or disables using default value per type or property.
954
+
955
+ ```typescript
956
+ import { Type, Property } from '@dipscope/type-manager';
957
+
958
+ @Type({
959
+ useDefaultValue: true
960
+ })
961
+ export class User
962
+ {
963
+ @Property(String, { useDefaultValue: false }) public name: string;
964
+ }
965
+ ```
966
+
967
+ Using default values is turned off by default. You can enable them globally using `TypeManager` configure method.
968
+
969
+ ### Use implicit conversion option
970
+
971
+ By default if declared type will not match provided during serialization or deserialization an error will be logged and result value will be undefined. This means that for example assigning `Number` to `String` will not work as `StringSerializer` expects `String`. However `Number` and other types can be converted to `String` for you when implicit conversion is enabled.
972
+
973
+ ```typescript
974
+ import { Type, Property } from '@dipscope/type-manager';
975
+
976
+ @Type()
977
+ export class User
978
+ {
979
+ @Property(String, { useImplicitConversion: true }) public name: string;
980
+ }
981
+ ```
982
+
983
+ With this any value which can be converted to `String` will be converted properly. Such behaviour works for other built in serializers and supported for custom ones. By default implicit conversion is turned off. You can enable it using `useImplicitConversion` option per type and property or enable globally using `TypeManager` configure method.
984
+
985
+ ## Defining configuration manually
986
+
987
+ There are circumstances when decorators cannot be used or you don't want to. For example you are using a 3rd party package and cannot decorate classes from it. Another use case when you want to configure some options globally. In such scenarios you can define the complete configuration through special static configure methods.
988
+
989
+ We have separate methods to configure each type manager option, so the provided examples can be simplified to avoid creating additional object. It is useful when you need to configure only one option. In our examples we are always use the main one to give you a general overview.
990
+
991
+ ### Configuring global options
992
+
993
+ There are several options which can be configured globally. For example let's override using of default value option so we don't have to specify it explicitly per type or property.
994
+
995
+ ```typescript
996
+ import { TypeManagerOptions, TypeOptionsBase } from '@dipscope/type-manager';
997
+
998
+ const typeOptionsBase: TypeOptionsBase<any> = {
999
+ useDefaultValue: true
1000
+ };
1001
+
1002
+ const typeManagerOptions: TypeManagerOptions = {
1003
+ typeOptionsBase: typeOptionsBase
1004
+ };
1005
+
1006
+ TypeManager.configure(typeManagerOptions);
1007
+ ```
1008
+
1009
+ For the full list of available global options check `TypeOptionsBase` definition or follow the documentation as we are going to touch them while we proceed.
1010
+
1011
+ ### Configuring options per type
1012
+
1013
+ Here is an example of declarative configuration which can be used for 3rd party or your own classes in addition to decorators.
1014
+
1015
+ ```typescript
1016
+ import { DateTime } from '@external-library';
1017
+ import { TypeManagerOptions, TypeFn, TypeOptions, PropertyName, PropertyOptions } from '@dipscope/type-manager';
1018
+
1019
+ const dateTimeOptions: TypeOptions<DateTime> = {
1020
+ alias: 'DateTime',
1021
+ serializer: new DateTimeSerializer()
1022
+ };
1023
+
1024
+ const userOptions: TypeOptions<User> = {
1025
+ alias: 'User',
1026
+ propertyOptionsMap: new Map<PropertyName, PropertyOptions<any>>(
1027
+ ['name', { typeArgument: String, serializable: true, alias: 'username' }],
1028
+ ['createdAt', { typeArgument: DateTime }]
1029
+ )
1030
+ };
1031
+
1032
+ const typeManagerOptions: TypeManagerOptions = {
1033
+ typeOptionsMap: new Map<TypeFn<any>, TypeOptions<any>>(
1034
+ [DateTime, dateTimeOptions],
1035
+ [User, userOptions]
1036
+ )
1037
+ };
1038
+
1039
+ TypeManager.configure(typeManagerOptions);
1040
+ ```
1041
+
1042
+ There is a well defined order to how type options are applied when using configure methods on one type. One should remember this when combining and overriding options in different places.
1043
+
1044
+ 1. Base type options are applied;
1045
+ 2. Decorator type options are applied;
1046
+ 3. Declarative type options are applied;
1047
+ 4. Property type options are applied;
1048
+
1049
+ Declarative configuration supports the same options as decorators. With such a configuration you can declare types like the following.
1050
+
1051
+ ```typescript
1052
+ export class User
1053
+ {
1054
+ public name: string;
1055
+ public createdAt: DateTime;
1056
+ }
1057
+ ```
1058
+
1059
+ Also if you are declaring only 3rd party classes the use case can be the following with [reflect-metadata](https://github.com/rbuckton/reflect-metadata).
1060
+
1061
+ ```typescript
1062
+ import 'reflect-metadata';
1063
+ import { Type, Property } from '@dipscope/type-manager';
1064
+
1065
+ @Type()
1066
+ export class User
1067
+ {
1068
+ @Property() public name: string;
1069
+ @Property() public createdAt: DateTime;
1070
+ }
1071
+ ```
1072
+
1073
+ And without [reflect-metadata](https://github.com/rbuckton/reflect-metadata).
1074
+
1075
+ ```typescript
1076
+ import { Type, Property } from '@dipscope/type-manager';
1077
+
1078
+ @Type()
1079
+ export class User
1080
+ {
1081
+ @Property(String) public name: string;
1082
+ @Property(DateTime) public createdAt: DateTime;
1083
+ }
1084
+ ```
1085
+
1086
+ ### Configuring usage of polymorphic types
1087
+
1088
+ Let's assume we are working with a shapes. To describe different types of shape we have to create an abstract class with several descendants.
1089
+
1090
+ ```typescript
1091
+ import { Type, Property } from '@dipscope/type-manager';
1092
+
1093
+ @Type()
1094
+ export abstract class Shape
1095
+ {
1096
+ @Property(String) public title: string;
1097
+ }
1098
+
1099
+ @Type()
1100
+ export class Rectangle extends Shape
1101
+ {
1102
+ @Property(Number) public width: number;
1103
+ @Property(Number) public height: number;
1104
+ }
1105
+
1106
+ @Type()
1107
+ export class Square extends Shape
1108
+ {
1109
+ @Property(Number) public width: number;
1110
+ }
1111
+
1112
+ @Type()
1113
+ export class Circle extends Shape
1114
+ {
1115
+ @Property(Number) public radius: number;
1116
+ }
1117
+ ```
1118
+
1119
+ Some other class declares a `shapes` property in it.
1120
+
1121
+ ```typescript
1122
+ import { Type, Property } from '@dipscope/type-manager';
1123
+
1124
+ @Type()
1125
+ export class Plot
1126
+ {
1127
+ @Property(Array, [Shape]) public shapes: Shape[];
1128
+ }
1129
+ ```
1130
+
1131
+ From the perspective of declaration everything looks ok but from the point of serialization some things may become complicated. Shapes property can store `Rectangle`, `Square` or `Circle`. Each of this classes have different properties. Here is an example of JSON.
1132
+
1133
+ ```json
1134
+ {
1135
+ "shapes": [
1136
+ {
1137
+ "title": "Cool rectangle",
1138
+ "width": 10,
1139
+ "height": 10
1140
+ },
1141
+ {
1142
+ "title": "Perfect square",
1143
+ "width": 10
1144
+ },
1145
+ {
1146
+ "title": "Simple circle",
1147
+ "radius": 6
1148
+ }
1149
+ ]
1150
+ }
1151
+ ```
1152
+
1153
+ During deserialization of this JSON to a `Plot` class we only aware that all plain objects inside an `Array` are somehow related to a `Shape` type. So any options to handle this?
1154
+
1155
+ Luckily we have a `TypeManager`. When you declaring you types using decorators or declarative style it builds inheritance graph between them which can be used during serialization and deserialization.
1156
+
1157
+ It uses 2 special configurable type options:
1158
+
1159
+ * `Discriminator` which defines a property inside an object which should be used to define a type.
1160
+ * `Discriminant` which represents a certain `Discriminator` value.
1161
+
1162
+ This options have default values if you have not configured them explicitly.
1163
+
1164
+ * Default value of discriminator is a `$type`. During deserialization `TypeManager` expects such property to be present inside a polymorphic object.
1165
+ * Default value of discriminant is a `ClassName` which determined based on the type function.
1166
+
1167
+ For proper deserialization of polymorphic types you have to provide such information inside your JSON.
1168
+
1169
+ ```json
1170
+ {
1171
+ "shapes": [
1172
+ {
1173
+ "$type": "Rectangle",
1174
+ "title": "Cool rectangle",
1175
+ "width": 10,
1176
+ "height": 10
1177
+ },
1178
+ {
1179
+ "$type": "Square",
1180
+ "title": "Perfect square",
1181
+ "width": 10
1182
+ },
1183
+ {
1184
+ "$type": "Circle",
1185
+ "title": "Simple circle",
1186
+ "radius": 6
1187
+ }
1188
+ ]
1189
+ }
1190
+ ```
1191
+
1192
+ Now your JSON will be handled properly and you will get `Rectangle`, `Square` and `Circle` class instances in return.
1193
+
1194
+ In some cases your `Discriminator` or `Discriminant` values will not match to our default ones. For example library like [Json.NET](https://www.newtonsoft.com/json) can be used on the backend side to send a response from your API. It uses `$type` property as `Discriminator` and full name of class as `Discriminant`. In such scenario our JSON may look like this.
1195
+
1196
+ ```json
1197
+ {
1198
+ "shapes": [
1199
+ {
1200
+ "$type": "Company.Api.Entities.Rectangle",
1201
+ "title": "Cool rectangle",
1202
+ "width": 10,
1203
+ "height": 10
1204
+ },
1205
+ {
1206
+ "$type": "Company.Api.Entities.Square",
1207
+ "title": "Perfect square",
1208
+ "width": 10
1209
+ },
1210
+ {
1211
+ "$type": "Company.Api.Entities.Circle",
1212
+ "title": "Simple circle",
1213
+ "radius": 6
1214
+ }
1215
+ ]
1216
+ }
1217
+ ```
1218
+
1219
+ To change `Discriminator` globally you have to use `TypeManager` configure method.
1220
+
1221
+ ```typescript
1222
+ import { TypeManagerOptions, TypeOptionsBase } from '@dipscope/type-manager';
1223
+
1224
+ const typeOptionsBase: TypeOptionsBase<any> = {
1225
+ discriminator: '$customType'
1226
+ };
1227
+
1228
+ const typeManagerOptions: TypeManagerOptions = {
1229
+ typeOptionsBase: typeOptionsBase
1230
+ };
1231
+
1232
+ TypeManager.configure(typeManagerOptions);
1233
+ ```
1234
+
1235
+ To change `Discriminant` you have to use per type configuration.
1236
+
1237
+ ```typescript
1238
+ import { TypeManagerOptions, TypeFn, TypeOptions, PropertyName, PropertyOptions } from '@dipscope/type-manager';
1239
+
1240
+ const rectangleOptions: TypeOptions<Rectangle> = {
1241
+ discriminant: 'Company.Api.Entities.Rectangle'
1242
+ };
1243
+
1244
+ const squareOptions: TypeOptions<Square> = {
1245
+ discriminant: 'Company.Api.Entities.Square'
1246
+ };
1247
+
1248
+ const circleOptions: TypeOptions<Circle> = {
1249
+ discriminant: 'Company.Api.Entities.Circle'
1250
+ };
1251
+
1252
+ const typeManagerOptions: TypeManagerOptions = {
1253
+ typeOptionsMap: new Map<TypeFn<any>, TypeOptions<any>>(
1254
+ [Rectangle, rectangleOptions],
1255
+ [Square, squareOptions],
1256
+ [Circle, circleOptions]
1257
+ )
1258
+ };
1259
+
1260
+ TypeManager.configure(typeManagerOptions);
1261
+ ```
1262
+
1263
+ As an alternative you can change `Discriminant` as the following using decorators.
1264
+
1265
+ ```typescript
1266
+ import { Type, Property } from '@dipscope/type-manager';
1267
+
1268
+ @Type({
1269
+ discriminant: 'Company.Api.Entities.Shape'
1270
+ })
1271
+ export abstract class Shape
1272
+ {
1273
+ @Property(String) public title: string;
1274
+ }
1275
+
1276
+ @Type({
1277
+ discriminant: 'Company.Api.Entities.Rectangle'
1278
+ })
1279
+ export class Rectangle extends Shape
1280
+ {
1281
+ @Property(Number) public width: number;
1282
+ @Property(Number) public height: number;
1283
+ }
1284
+
1285
+ @Type({
1286
+ discriminant: 'Company.Api.Entities.Square'
1287
+ })
1288
+ export class Square extends Shape
1289
+ {
1290
+ @Property(Number) public width: number;
1291
+ }
1292
+
1293
+ @Type({
1294
+ discriminant: 'Company.Api.Entities.Circle'
1295
+ })
1296
+ export class Circle extends Shape
1297
+ {
1298
+ @Property(Number) public radius: number;
1299
+ }
1300
+ ```
1301
+
1302
+ By default `Discriminator` is not preserved inside objects and only used during deserialization. You can change this behavior by enabling preserving of discriminator globally or per type.
1303
+
1304
+ ```typescript
1305
+ import { TypeManagerOptions, TypeOptionsBase } from '@dipscope/type-manager';
1306
+
1307
+ const typeOptionsBase: TypeOptionsBase<any> = {
1308
+ preserveDiscriminator: true
1309
+ };
1310
+
1311
+ const typeManagerOptions: TypeManagerOptions = {
1312
+ typeOptionsBase: typeOptionsBase
1313
+ };
1314
+
1315
+ TypeManager.configure(typeManagerOptions);
1316
+ ```
1317
+
1318
+ With this option enabled discriminator will be present in output data.
1319
+
1320
+ ### Configuring naming convention
1321
+
1322
+ Naming convention specifies how each declared property of a type should be treated when reading it from JSON. By default names are read as is. Let's assume we have a `User` class in camel case naming convention for properties.
1323
+
1324
+ ```typescript
1325
+ import { Type, Property } from '@dipscope/type-manager';
1326
+
1327
+ @Type()
1328
+ export class User
1329
+ {
1330
+ @Property(String) public name: string;
1331
+ @Property(Number) public loginCount: number;
1332
+ @Property(DateTime) public createdAt: DateTime;
1333
+ }
1334
+ ```
1335
+
1336
+ Our JSON should match the same naming convention to work properly.
1337
+
1338
+ ```json
1339
+ [
1340
+ {
1341
+ "name": "Dmitry",
1342
+ "loginCount": 10,
1343
+ "createdAt": "2021-02-22T20:15:00.000Z"
1344
+ },
1345
+ {
1346
+ "name": "Alex",
1347
+ "loginCount": 25,
1348
+ "createdAt": "2021-02-22T21:15:00.000Z"
1349
+ },
1350
+ {
1351
+ "name": "Anna",
1352
+ "loginCount": 3,
1353
+ "createdAt": "2021-02-22T21:15:23.000Z"
1354
+ }
1355
+ ]
1356
+ ```
1357
+
1358
+ But what to do if we don't control the JSON naming convention so it comes to us in a snake case?
1359
+
1360
+ ```json
1361
+ [
1362
+ {
1363
+ "name": "Dmitry",
1364
+ "login_count": 10,
1365
+ "created_at": "2021-02-22T20:15:00.000Z"
1366
+ },
1367
+ {
1368
+ "name": "Alex",
1369
+ "login_count": 25,
1370
+ "created_at": "2021-02-22T21:15:00.000Z"
1371
+ },
1372
+ {
1373
+ "name": "Anna",
1374
+ "login_count": 3,
1375
+ "created_at": "2021-02-22T21:15:23.000Z"
1376
+ }
1377
+ ]
1378
+ ```
1379
+
1380
+ We can still parse such a JSON by specifying an alias for each property but this will become a pain in a while.
1381
+
1382
+ ```typescript
1383
+ import { Type, Property } from '@dipscope/type-manager';
1384
+
1385
+ @Type()
1386
+ export class User
1387
+ {
1388
+ @Property(String) public name: string;
1389
+ @Property(Number, { alias: 'login_count' }) public loginCount: number;
1390
+ @Property(DateTime, { alias: 'created_at' }) public createdAt: DateTime;
1391
+ }
1392
+ ```
1393
+
1394
+ `TypeManager` supports several naming conventions we can use to avoid dealing with aliases.
1395
+
1396
+ * Camel case [camelCase];
1397
+ * Flat case [flatcase];
1398
+ * Flat upper case [FLATCASE];
1399
+ * Kebab case [kebab-kase];
1400
+ * Kebab upper case [KEBAB-CASE];
1401
+ * Pascal case [PascalCase];
1402
+ * Snake case [snake_case];
1403
+ * Snake upper case [SNAKE_CASE];
1404
+
1405
+ To set one we have to configure global options.
1406
+
1407
+ ```typescript
1408
+ import { TypeManagerOptions, TypeOptionsBase, SnakeCaseNamingConvention } from '@dipscope/type-manager';
1409
+
1410
+ const typeOptionsBase: TypeOptionsBase<any> = {
1411
+ namingConvention: new SnakeCaseNamingConvention()
1412
+ };
1413
+
1414
+ const typeManagerOptions: TypeManagerOptions = {
1415
+ typeOptionsBase: typeOptionsBase
1416
+ };
1417
+
1418
+ TypeManager.configure(typeManagerOptions);
1419
+ ```
1420
+
1421
+ Now all property names will be converted to snake case while reading them from JSON. If you have not found suitable naming convention you can easily implement your own. Read more about [creating a custom naming convention](#defining-custom-naming-convention) in a separate section.
1422
+
1423
+ ### Configuring reference handler
1424
+
1425
+ Reference handler defines how references to the same objects including a circular one should be treated. We have several reference handlers: direct, lead and path. Each of them can be used globally or per type.
1426
+
1427
+ * Direct reference handler preserves object references without making any special changes;
1428
+ * Path reference handler preserves object references using JSONPath notation;
1429
+ * Lead reference handler preserves object references excluding a circular one. When circular reference is detected it will be set to undefined;
1430
+
1431
+ There is nothing better to show the difference than code. For example we have two classes which reference each other:
1432
+
1433
+ ```typescript
1434
+ import { Type, Property } from '@dipscope/type-manager';
1435
+
1436
+ @Type()
1437
+ class User
1438
+ {
1439
+ @Property(() => Company) public company: Company;
1440
+ }
1441
+
1442
+ @Type()
1443
+ class Company
1444
+ {
1445
+ @Property(() => User) public user: User;
1446
+ }
1447
+ ```
1448
+
1449
+ Somewhere in code you have such a logic:
1450
+
1451
+ ```typescript
1452
+ import { TypeManager } from '@dipscope/type-manager';
1453
+
1454
+ const user = new User();
1455
+ const company = new Company();
1456
+
1457
+ user.company = company;
1458
+ company.user = user;
1459
+
1460
+ const result = TypeManager.serialize(User, user);
1461
+ ```
1462
+
1463
+ Here are results returned by different reference handlers:
1464
+
1465
+ ```typescript
1466
+ // Direct reference handler...
1467
+ { company: { user: result } };
1468
+
1469
+ // Path reference handler...
1470
+ { company: { user: { $ref: '$' } } };
1471
+
1472
+ // Lead reference handler...
1473
+ { company: { user: undefined };
1474
+ ```
1475
+
1476
+ As you can see `DirectReferenceHandler` does not make changes to your data and completely fine until you have to convert circular reference structure to a string. `JSON.stringify` method which we are using under the hood does not support such conversions so you will encounter an error. In this case you can select another reference handler. For example `PathReferenceHandler` which produces JSON string using JSONPath format for circular references supported by many libraries. Or you can simply ignore circular reference when it should be converted to a string and use `LeadReferenceHandler`. To change default reference handler you have to use `TypeManager` configure methods.
1477
+
1478
+ ```typescript
1479
+ import { TypeManagerOptions, TypeOptionsBase, PathReferenceHandler } from '@dipscope/type-manager';
1480
+
1481
+ const typeOptionsBase: TypeOptionsBase<any> = {
1482
+ referenceHandler: new PathReferenceHandler()
1483
+ };
1484
+
1485
+ const typeManagerOptions: TypeManagerOptions = {
1486
+ typeOptionsBase: typeOptionsBase
1487
+ };
1488
+
1489
+ TypeManager.configure(typeManagerOptions);
1490
+ ```
1491
+
1492
+ With such configuration any reference will be handled using JSONPath so you are completely free from errors during conversion to a string.
1493
+
1494
+ ## Advanced usage
1495
+
1496
+ Our goal is to cover as much use cases as possible without making you to write additional code but there always be an application specific case. With that in mind we allow you to customize and extend each part of our pipeline.
1497
+
1498
+ ### Defining custom data
1499
+
1500
+ You can attach you custom metadata to our decorators using `customData` option available on `Type` and `Property`.
1501
+
1502
+ ```typescript
1503
+ import { Type, Property } from '@dipscope/type-manager';
1504
+
1505
+ @Type({
1506
+ customData: { rank: 1 }
1507
+ })
1508
+ class User
1509
+ {
1510
+ @Property(String, { customData: { priority: 10 } }) public name: string;
1511
+ }
1512
+ ```
1513
+
1514
+ This allows you to get it later in serializers, factories, injectors or your code and perform specific actions. Besides pipeline you can get this data in any place you want using `TypeManager`.
1515
+
1516
+ ```typescript
1517
+ import { TypeManager } from '@dipscope/type-manager';
1518
+
1519
+ const userMetadata = TypeManager.extractTypeMetadata(User);
1520
+ const customData = userMetadata.customData;
1521
+
1522
+ // Do something with type custom data...
1523
+
1524
+ for (const propertyMetadata of userMetadata.propertyMetadataMap.values())
1525
+ {
1526
+ const propertyCustomData = propertyMetadata.customData;
1527
+
1528
+ // Do something with property custom data...
1529
+ }
1530
+ ```
1531
+
1532
+ ### Defining custom serializer
1533
+
1534
+ You can create your own serializer or replace built in one. First you have to implement `Serializer` interface. It declares `serialize` and `deserialize` methods. Serialize method is called during conversion of `JavaScript` object instance into a plain object. Deserialize method is called during backward conversion. Here is an example of possible definition for custom `DateTime` class.
1535
+
1536
+ ```typescript
1537
+ import { Serializer, TypeLike, SerializerContext } from '@dipscope/type-manager';
1538
+ import { Fn } from '@app/module';
1539
+
1540
+ export class DateTimeSerializer implements Serializer<DateTime>
1541
+ {
1542
+ public serialize(x: TypeLike<DateTime>, serializerContext: SerializerContext<DateTime>): TypeLike<string>
1543
+ {
1544
+ if (Fn.isUndefined(x))
1545
+ {
1546
+ return serializerContext.serializedDefaultValue;
1547
+ }
1548
+
1549
+ if (Fn.isNull(x))
1550
+ {
1551
+ return x;
1552
+ }
1553
+
1554
+ if (Fn.isDateTime(x))
1555
+ {
1556
+ return x.toIsoString();
1557
+ }
1558
+
1559
+ if (serializerContext.log.errorEnabled)
1560
+ {
1561
+ serializerContext.log.error(`${serializerContext.path}: cannot serialize value as date time.`, x);
1562
+ }
1563
+
1564
+ return undefined;
1565
+ }
1566
+
1567
+ public deserialize(x: TypeLike<string>, serializerContext: SerializerContext<DateTime>): TypeLike<DateTime>
1568
+ {
1569
+ if (Fn.isUndefined(x))
1570
+ {
1571
+ return serializerContext.deserializedDefaultValue;
1572
+ }
1573
+
1574
+ if (Fn.isNull(x))
1575
+ {
1576
+ return x;
1577
+ }
1578
+
1579
+ if (Fn.isString(x))
1580
+ {
1581
+ return DateTime.fromIsoString(x);
1582
+ }
1583
+
1584
+ if (serializerContext.log.errorEnabled)
1585
+ {
1586
+ serializerContext.log.error(`${serializerContext.path}: cannot deserialize value as date time.`, x);
1587
+ }
1588
+
1589
+ return undefined;
1590
+ }
1591
+ }
1592
+ ```
1593
+
1594
+ This example follows internal conventions and gives you a picture of how real serializer may look like. `TypeManager` does not perform any checks and just passes values directly to serializer. Thats why input values can be undefined, null or others depending from what is stored inside certain property. `TypeLike` is an internal type to declare this behaviour.
1595
+
1596
+ Serializer implementation is fully responsible for return result. You can get default values, custom data and other options specified in configuration from current serializer context and react accordingly. For example you can check if implicit conversion is enabled and convert any value to the target one.
1597
+
1598
+ When you are finished with definitions there are two possible ways to register a serializer. You can use decorators.
1599
+
1600
+ ```typescript
1601
+ import { Type, Serializer } from '@dipscope/type-manager';
1602
+
1603
+ @Type({
1604
+ serializer: new DateTimeSerializer()
1605
+ })
1606
+ export class DateTime
1607
+ {
1608
+ ...
1609
+ }
1610
+ ```
1611
+
1612
+ Or declarative configuration.
1613
+
1614
+ ```typescript
1615
+ import { TypeManager } from '@dipscope/type-manager';
1616
+
1617
+ TypeManager.configureTypeOptions(DateTime, {
1618
+ alias: 'DateTime',
1619
+ serializer: new DateTimeSerializer()
1620
+ });
1621
+ ```
1622
+
1623
+ With declarative configuration it is possible to override built in serializers if it's behaviour not suitable for your use cases. Also you can register serializers for types we not yet cover.
1624
+
1625
+ ### Defining custom injector
1626
+
1627
+ In modern world we are always use some kind of framework to build our application. It is definitely already have a configured dependency injection container so let's configure `TypeManager` for using it instead of build in one. You have to implement `Injector` interface with only one method. Here how it may look like in `Angular`.
1628
+
1629
+ ```typescript
1630
+ import { Injector, TypeMetadata } from '@dipscope/type-manager';
1631
+ import { Injector as AngularInjector } from '@angular/core';
1632
+
1633
+ export class CustomInjector implements Injector
1634
+ {
1635
+ private readonly angularInjector: AngularInjector;
1636
+
1637
+ public constructor(angularInjector: AngularInjector)
1638
+ {
1639
+ this.angularInjector = angularInjector;
1640
+
1641
+ return;
1642
+ }
1643
+
1644
+ public get<TType>(typeMetadata: TypeMetadata<TType>): TType | undefined
1645
+ {
1646
+ return this.angularInjector.get(typeMetadata.typeFn);
1647
+ }
1648
+ }
1649
+ ```
1650
+
1651
+ In general you have to get framework injector or create it manually. Then call method to get and instance by type when one is requested. Implementations can differ but we hope idea is clear. When you are finished with definitions you have to register custom injector for a `TypeManager`.
1652
+
1653
+ ```typescript
1654
+ import { TypeManager } from '@dipscope/type-manager';
1655
+ import { Injector as AngularInjector } from '@angular/core';
1656
+
1657
+ const angularInjector: AngularInjector = ...; // Get framework injector in core module for example.
1658
+
1659
+ TypeManager.configureTypeOptionsBase({
1660
+ injector: new CustomInjector(angularInjector)
1661
+ });
1662
+ ```
1663
+
1664
+ Now types will be resolved using framework injector.
1665
+
1666
+ ### Defining custom factory
1667
+
1668
+ When you want to apply additional logic to how types are constructed you can specify custom factory globally or per type. Let's say you want to init some properties based on your custom data specified for a type. You can do this by extending default `TypeFactory`.
1669
+
1670
+ ```typescript
1671
+ import { TypeContext, Injector, TypeFactory } from '@dipscope/type-manager';
1672
+
1673
+ export class CustomTypeFactory extends TypeFactory
1674
+ {
1675
+ public build<TType>(typeContext: TypeContext<TType>, injector: Injector): TType
1676
+ {
1677
+ // Build any type.
1678
+ const type = super.build(typeContext, injector) as any;
1679
+
1680
+ // Resolve custom data.
1681
+ const typeMetadata = typeContext.typeMetadata;
1682
+ const customData = typeMetadata.customData;
1683
+
1684
+ // Process custom data.
1685
+ for (const propertyName in customData)
1686
+ {
1687
+ type[propertyName] = customData[propertyName];
1688
+ }
1689
+
1690
+ return type;
1691
+ }
1692
+ }
1693
+ ```
1694
+
1695
+ When you are finished with definitions there are two possible ways to register a factory. You can use decorators.
1696
+
1697
+ ```typescript
1698
+ import { Type, Factory } from '@dipscope/type-manager';
1699
+
1700
+ @Type({
1701
+ customData: { rank: 1 },
1702
+ factory: new CustomTypeFactory()
1703
+ })
1704
+ export class User
1705
+ {
1706
+ ...
1707
+ }
1708
+ ```
1709
+
1710
+ Or declarative configuration.
1711
+
1712
+ ```typescript
1713
+ import { TypeManager } from '@dipscope/type-manager';
1714
+
1715
+ // Overriding only for user type.
1716
+ TypeManager.configureTypeOptions(User, {
1717
+ customData: { rank: 1 },
1718
+ factory: new CustomTypeFactory()
1719
+ });
1720
+
1721
+ // Overriding for any type.
1722
+ TypeManager.configureTypeOptionsBase({
1723
+ factory: new CustomTypeFactory()
1724
+ });
1725
+ ```
1726
+
1727
+ ### Defining custom naming convention
1728
+
1729
+ To define custom naming convention you have to implement `NamingConvention` interface with only one `convert` method. Here is an example implementation of camel case naming convention.
1730
+
1731
+ ```typescript
1732
+ import { NamingConvention, getWords } from '@dipscope/type-manager';
1733
+
1734
+ export class CamelCaseNamingConvention implements NamingConvention
1735
+ {
1736
+ public convert(name: string): string
1737
+ {
1738
+ return getWords(name).reduce(this.reduce, '');
1739
+ }
1740
+
1741
+ private reduce(result: string, word: string, index: number): string
1742
+ {
1743
+ if (word.length === 0)
1744
+ {
1745
+ return result;
1746
+ }
1747
+
1748
+ const wordLowerCased = word.toLowerCase();
1749
+
1750
+ if (index === 0)
1751
+ {
1752
+ return wordLowerCased;
1753
+ }
1754
+
1755
+ return `${result}${wordLowerCased[0].toUpperCase()}${wordLowerCased.slice(1)}`;
1756
+ }
1757
+ }
1758
+ ```
1759
+
1760
+ Public `convert` method receives a property name as it declared in a class. You have to call internal `getWords` function on it which will split property name into array of the words. In the `reduce` function you can combine this words to whatever string you want. When you are finished with definitions you have to register custom naming convention for a `TypeManager`.
1761
+
1762
+ ```typescript
1763
+ import { TypeManager } from '@dipscope/type-manager';
1764
+
1765
+ TypeManager.configureTypeOptionsBase({
1766
+ namingConvention: new CamelCaseNamingConvention()
1767
+ });
1768
+ ```
1769
+
1770
+ Now property names will be resolved using your custom naming convention.
1771
+
1772
+ ## Use cases
1773
+
1774
+ This section describes certain use cases to separate them from the main documentation part. We will point to a concrete place you should read to setup what is necessary.
1775
+
1776
+ ### Built in serializers
1777
+
1778
+ Here is a list of types with built in serializers.
1779
+
1780
+ * Array;
1781
+ * ArrayBuffer;
1782
+ * Boolean;
1783
+ * DataView;
1784
+ * Date;
1785
+ * Float32Array;
1786
+ * Float64Array;
1787
+ * Int8Array;
1788
+ * Int16Array;
1789
+ * Int32Array;
1790
+ * Map;
1791
+ * Number;
1792
+ * Set;
1793
+ * String;
1794
+ * Uint8Array;
1795
+ * Uint8ClampedArray;
1796
+ * Uint16Array;
1797
+ * Uint32Array;
1798
+
1799
+ For these you don't have to do anything to make them work. You are free to [create a custom serializer](#defining-custom-serializer) or override built in one if it does not cover your use case.
1800
+
1801
+ ### Circular object references
1802
+
1803
+ We have a great support for circular references with different behaviour when they are detected. Read [configuring reference handler](#configuring-reference-handler) section for more info.
1804
+
1805
+ ### Dependency injection and immutable types
1806
+
1807
+ Follow the steps described in [inject decorator](#inject-decorator) section. To integrate our injection system with you yours check [defining custom injector](#defining-custom-injector) section.
1808
+
1809
+ ### Different case usage in class and JSON
1810
+
1811
+ If your cases differs between class and JSON. For example `camelCase` vs `snake_case`. You can setup naming convention to use during serialization and deserialization. Follow the steps described in [configuring naming convention](#configuring-naming-convention) section.
1812
+
1813
+ ### Enum types
1814
+
1815
+ Enum types are supported but require special handling. This is because of how enums are represented after compiling them to `JavaScript`. You can know more about how to define them in a [property decorator](#property-decorator) section. If you are interested about the `Enum` compilation details you can check the official [documentation](https://www.typescriptlang.org/docs/handbook/enums.html).
1816
+
1817
+ ### Generic types
1818
+
1819
+ Generic types are supported and you can define them. Read [property decorator](#property-decorator) section for more info.
1820
+
1821
+ ### Integration with Angular
1822
+
1823
+ With `Angular` you do not need to install [reflect-metadata](https://github.com/rbuckton/reflect-metadata) as it is already included in `core-js`. However, you still need to instruct CLI to include it in the build. This can be achieved simply by adding `import 'reflect-metadata';` to you `main.ts` file.
1824
+
1825
+ To make `Angular` injector work for you a custom `Injector` needs to be implemented. Check [defining custom injector](#defining-custom-injector) section for more info.
1826
+
1827
+ ### Polymorphic types
1828
+
1829
+ Polymorphic types are supported. In most cases additional configuration is required. Check [configuring usage of polymorphic types](#configuring-usage-of-polymorphic-types) section for more info.
1830
+
1831
+ ## Versioning
1832
+
1833
+ We use [SemVer](http://semver.org/) for versioning. For the versions available, see the versions section on [NPM project page](https://www.npmjs.com/package/@dipscope/type-manager).
1834
+
1835
+ See information about breaking changes, release notes and migration steps between versions in [CHANGELOG.md](https://github.com/dipscope/TypeManager.TS/blob/master/CHANGELOG.md) file.
1836
+
1837
+ ## Contributing
1838
+
1839
+ Please read [CONTRIBUTING.md](https://github.com/dipscope/TypeManager.TS/blob/master/CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us.
1840
+
1841
+ ## Authors
1842
+
1843
+ * **Dmitry Pimonov** - *Initial work* - [dpimonov](https://github.com/dpimonov)
1844
+
1845
+ See also the list of [contributors](https://github.com/dipscope/TypeManager.TS/contributors) who participated in this project.
1846
+
1847
+ ## Notes
1848
+
1849
+ Thanks for checking this package.
1850
+
1851
+ Feel free to create an issue if you find any mistakes in documentation or have any improvements in mind.
1852
+
1853
+ We wish you good luck and happy coding!
1854
+
1855
+ ## License
1856
+
1857
+ This project is licensed under the Apache 2.0 License - see the [LICENSE.md](https://github.com/dipscope/TypeManager.TS/blob/master/LICENSE.md) file for details.