@dipscope/type-manager 4.0.3 → 4.1.1

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