Skip to content

Commit

Permalink
docs: add a caveat about serialization 2/2 (#2902)
Browse files Browse the repository at this point in the history
  • Loading branch information
marcpicaud committed Mar 13, 2022
1 parent db3bf34 commit dfb7e10
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions docs/docs/usage-with-nestjs.md
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,26 @@ app.use((req, res, next) => {
});
```

## Serialization caveat

[NestJS built-in serialization](https://docs.nestjs.com/techniques/serialization) relies on [class-transformer](https://github.com/typestack/class-transformer). Since MikroORM wraps every single entity relation in a `Reference` or a `Collection` instance (for type-safety), this will make the built-in `ClassSerializerInterceptor` blind to any wrapped relations. In other words, if you return MikroORM entities from your HTTP or WebSocket handlers, all of their relations will NOT be serialized.

Luckily, MikroORM provides a [serialization API](https://mikro-orm.io/docs/serializing) which can be used in lieu of `ClassSerializerInterceptor`.

```typescript
@Entity()
export class Book {
@Property({ hidden: true }) // --> Equivalent of class-transformer's `@Exclude`
hiddenField: number = Date.now();

@Property({ persist: false }) // --> Will only exist in memory (and will be serialized). Similar to class-transformer's `@Expose()`
count?: number;

@ManyToOne({ serializer: value => value.name, serializedName: 'authorName' }) // Equivalent of class-transformer's `@Transform()`
author: Author;
}
```

## Testing

The `@mikro-orm/nestjs` package exposes `getRepositoryToken()` function that returns prepared token based on a given entity to allow mocking the repository.
Expand Down

0 comments on commit dfb7e10

Please sign in to comment.