You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/techniques/serialization.md
+14-15Lines changed: 14 additions & 15 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -37,14 +37,14 @@ Now consider a controller with a method handler that returns an instance of this
37
37
findOne(): UserEntity {
38
38
returnnewUserEntity({
39
39
id: 1,
40
-
firstName: 'Kamil',
41
-
lastName: 'Mysliwiec',
40
+
firstName: 'John',
41
+
lastName: 'Doe',
42
42
password: 'password',
43
43
});
44
44
}
45
45
```
46
46
47
-
> **Warning** Note that we must return an instance of the class. If you return a plain JavaScript object, for example, `{{ '{' }} user: new UserEntity() {{ '}' }}`, the object won't be properly serialized.
47
+
> **Warning** Note that we must return an instance of the class. If you return a plain JavaScript object, for example, `{{ '{' }} user: new UserEntity() {{ '}' }}`, the object won't be properly serialized.
48
48
49
49
> info **Hint** The `ClassSerializerInterceptor` is imported from `@nestjs/common`.
50
50
@@ -53,44 +53,43 @@ When this endpoint is requested, the client receives the following response:
53
53
```json
54
54
{
55
55
"id": 1,
56
-
"firstName": "Kamil",
57
-
"lastName": "Mysliwiec"
56
+
"firstName": "John",
57
+
"lastName": "Doe"
58
58
}
59
59
```
60
60
61
61
Note that the interceptor can be applied application-wide (as covered [here](https://docs.nestjs.com/interceptors#binding-interceptors)). The combination of the interceptor and the entity class declaration ensures that **any** method that returns a `UserEntity` will be sure to remove the `password` property. This gives you a measure of centralized enforcement of this business rule.
62
62
63
+
#### Transform plain objects
63
64
64
-
#### Using the SerializeOptions to transform plain objects to the class instance.
65
-
66
-
You could enforce transformations at the controller level by stating `@SerializeOptions({{ '{' }} type {{ ':' }} <CLASS> {{ '}' }})` to transform all responses to the instance. Doing so will ensure that decorators on the class will always be applied, even if plain objects are returned. This allows for terser code, without the added verbosity of instantiating the class or calling `plainToInstance` repeatedly.
65
+
You can enforce transformations at the controller level by using the `@SerializeOptions({ type: <CLASS> })` decorator. This ensures that all responses are transformed into instances of the specified class, applying any decorators from class-validator or class-transformer, even when plain objects are returned. This approach leads to cleaner code without the need to repeatedly instantiate the class or call `plainToInstance`.
67
66
68
-
In this example, even though a plain js object was returned in both conditional statements, they will all be converted into `UserEntity` with annotated class-validator or class-transformer decorators applied.
67
+
In the example below, despite returning plain JavaScript objects in both conditional branches, they will be automatically converted into `UserEntity`instances, with the relevant decorators applied:
69
68
70
69
```typescript
71
70
@UseInterceptors(ClassSerializerInterceptor)
71
+
@SerializeOptions({ type: UserEntity })
72
72
@Get()
73
-
@SerializeOptions({ type : UserEntity })
74
73
findOne(@Query() { id }: { id: number }): UserEntity {
75
74
if (id===1) {
76
75
return {
77
76
id: 1,
78
-
firstName: 'Kamil',
79
-
lastName: 'Mysliwiec',
77
+
firstName: 'John',
78
+
lastName: 'Doe',
80
79
password: 'password',
81
80
};
82
81
}
83
82
84
83
return {
85
84
id: 2,
86
-
firstName: 'Kamil2',
87
-
lastName: 'Mysliwiec2',
85
+
firstName: 'Kamil',
86
+
lastName: 'Mysliwiec',
88
87
password: 'password2',
89
88
};
90
89
}
91
90
```
92
91
93
-
> info **Hint** By stating the expecting controller return type, we can take advantage of Typescript to check if the returned plain object conforms to the DTO/entity shape. `plainToInstance`' does not hint if the plain object conforms to the the DTO/entity class instance you are transforming it into (somewhat equivalent to typecasting). This could lead to bugs in your application.
92
+
> info **Hint** By specifying the expected return type for the controller, you can leverage TypeScript's type-checking capabilities to ensure that the returned plain object adheres to the shape of the DTO or entity. The `plainToInstance` function doesn't provide this level of type hinting, which can lead to potential bugs if the plain object doesn't match the expected DTO or entity structure.
0 commit comments