@dipscope/type-manager 4.1.1 → 5.0.0-beta.0

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