Cast entity to dto

Solution:

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:

  1. npm install --save @fabio.formosa/metamorphosis-nest
    
  2. import { MetamorphosisNestModule } from '@fabio.formosa/metamorphosis-nest';
    
    @Module({
      imports: [MetamorphosisModule.register()],
      ...
    }
    export class MyApp{ }
    
  3. 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 .