Just wondering the best way to convert a NestJS entity object to a DTO.
Lets say I have the following:
import { IsString, IsNumber, IsBoolean } from 'class-validator';
import { Exclude } from 'class-transformer';
export class PhotoSnippetDto {
@IsNumber()
readonly id: number;
@IsString()
readonly name: string;
constructor(props) {
Object.assign(this, props);
}
}
export class Photo {
@IsNumber()
id: number;
@IsString()
name: string;
@IsString()
description: string;
@IsString()
filename: string;
@IsNumber()
views: number;
@IsBoolean()
isPublished: boolean;
@Exclude()
@IsString()
excludedPropery: string;
constructor(props) {
Object.assign(this, props);
}
}
@Controller()
export class AppController {
@Get()
@UseInterceptors(ClassSerializerInterceptor)
root(): PhotoSnippetDto {
const photo = new Photo({
id: 1,
name: 'Photo 1',
description: 'Photo 1 description',
filename: 'photo.png',
views: 10,
isPublished: true,
excludedPropery: 'Im excluded'
});
return new PhotoSnippetDto(photo);
}
}
I was expecting the ClassSerializerInterceptor to serialize the photo object to the DTO and return something like this:
{
id: 1,
name: 'Photo 1'
}
But I'm getting a response containing all the properties still:
{
id = 1,
name = 'Photo 1',
description = 'Photo 1 description',
filename = 'file.png',
views = 10,
isPublished = true
}
I basically want to strip out all properties that are not defined in the DTO.
I know the ClassSerializerInterceptor works perfectly when using @Exclude(), I was just also expecting it to remove undefined properties also.
I'm curious as to the best way to go about this? I know I could do something like:
@Get('test')
@UseInterceptors(ClassSerializerInterceptor)
test(): PhotoSnippetDto {
const photo = new Photo({
id: 1,
name: 'Photo 1',
description: 'Photo 1 description',
filename: 'photo.png',
views: 10,
isPublished: true,
excludedPropery: 'Im excluded'
});
const { id, name } = photo;
return new PhotoSnippetDto({id, name});
}
But if I ever want to add another property to the response I'd have to do more than just add the new property to the class.. I'm wondering if there's a better 'Nest way' of doing it.
Short answer: Entities may be part of a business domain. Thus, they can implement behavior and be applied to different use cases within the domain. DTOs are used only to transfer data from one process or context to another.
Using Model Mapper Library Thus, we can use model mapper to convert entity to dto or dto to entities. First, we need to add model mapper dependency. Next, we can create a @Bean factory method to create ModelMapper instance. This way, the model mapper instance will be available for injection on the application level.
So based on Jesse's awesome answer I ended up creating the DTO using @Exclude() and @Expose() to remove all but exposed properties:
import { IsString, IsEmail } from 'class-validator';
import { Exclude, Expose } from 'class-transformer';
@Exclude()
export class PhotoSnippetDto {
@Expose()
@IsNumber()
readonly id: number;
@Expose()
@IsString()
readonly name: string;
}
And then I created a generic transform interceptor that calls plainToclass to convert the object:
import { Injectable, NestInterceptor, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { plainToClass } from 'class-transformer';
interface ClassType<T> {
new(): T;
}
@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<Partial<T>, T> {
constructor(private readonly classType: ClassType<T>) {}
intercept(context: ExecutionContext, call$: Observable<Partial<T>>, ): Observable<T> {
return call$.pipe(map(data => plainToClass(this.classType, data)));
}
}
And then use this interceptor to transform the data to any type:
@Get('test')
@UseInterceptors(new TransformInterceptor(PhotoSnippetDto))
test(): PhotoSnippetDto {
const photo = new Photo({
id: 1,
name: 'Photo 1',
description: 'Photo 1 description',
filename: 'photo.png',
views: 10,
isPublished: true,
excludedPropery: 'Im excluded'
});
return photo;
}
Which gives me what I wanted:
{
id: 1,
name: 'Photo 1'
}
Definitely feels more nest-like! I can use the same interceptor where ever I need and to change the response I only ever need to change the DTOs.
Happy days.
One possible option is to mark your DTO object with the @Exclude
and @Expose
decorators and then do a conversion with plainToClass
:
@Exclude()
export class PhotoSnippetDto {
@Expose()
@IsNumber()
readonly id: number;
@Expose()
@IsString()
readonly name: string;
}
Assuming you've decorated as above you can then do: const dto = plainToClass(PhotoSnippetDto, photo);
The resulting object is in the form you expect with only id
and name
showing up on the final object. If you decide later to expose more properties you can simply add them to your DTO and tag them with @Expose
.
This approach also allows you to remove the constructor from your DTO that is using Object.assign
For all type conversions, I've developed a library metamorphosis-nestjs to ease conversions of objects.
It adds to NestJS the missing concept of a injectable conversion service for all conversions provided by your converters, early registered into the conversion service (like conversion service provided by Spring Framework in Java app).
So in your case:
npm install --save @fabio.formosa/metamorphosis-nest
import { MetamorphosisNestModule } from '@fabio.formosa/metamorphosis-nest';
@Module({
imports: [MetamorphosisModule.register()],
...
}
export class MyApp{ }
import { Convert, Converter } from '@fabio.formosa/metamorphosis';
@Injectable()
@Convert(Photo, PhotoSnippetDto )
export default class PhotoToPhotoSnippetDtoConverter implements Converter<Photo,
PhotoSnippetDto> {
public convert(source: Photo): PhotoSnippetDto {
const target = new PhotoSnippetDto();
target.id = source.id;
target.name = source.name;
return target;
}
}
Finally you can inject and use conversionService whatever you want:
const photoSnippetDto = <PhotoSnippetDto> await this.convertionService.convert(photo, PhotoSnippetDto);
In relation to other answers of this question, you can use into your convert method plainToClass:
@Injectable()
@Convert(Photo, PhotoSnippetDto )
export default class PhotoToPhotoSnippetDtoConverter implements Converter<Photo, PhotoSnippetDto> {
public convert(source: Photo): PhotoSnippetDto {
return plainToClass(PhotoSnippetDto, source);
}
}
and, if you want, you can call conversionService also within interceptor.
Get the README to find out examples and all benefits of metamorphosis-nestjs .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With