Cast entity to dto












2















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.










share|improve this question





























    2















    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.










    share|improve this question



























      2












      2








      2


      1






      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.










      share|improve this question
















      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.







      node.js typescript nestjs






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 19 '18 at 17:08







      Lewsmith

















      asked Nov 19 '18 at 16:12









      LewsmithLewsmith

      458




      458
























          2 Answers
          2






          active

          oldest

          votes


















          3














          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






          share|improve this answer
























          • Thanks Jesse, I didn't realise @Exclude can be used class-wide. This is exactly what I was after!

            – Lewsmith
            Nov 20 '18 at 0:50






          • 1





            @Lewsmith No problem! Glad I could help out. Thanks a lot for sharing the full implementation of the interceptor too that looks like a great solution! Might even steal it for a future Nest app :P

            – Jesse Carter
            Nov 20 '18 at 1:51



















          2














          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.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53378667%2fcast-entity-to-dto%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            3














            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






            share|improve this answer
























            • Thanks Jesse, I didn't realise @Exclude can be used class-wide. This is exactly what I was after!

              – Lewsmith
              Nov 20 '18 at 0:50






            • 1





              @Lewsmith No problem! Glad I could help out. Thanks a lot for sharing the full implementation of the interceptor too that looks like a great solution! Might even steal it for a future Nest app :P

              – Jesse Carter
              Nov 20 '18 at 1:51
















            3














            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






            share|improve this answer
























            • Thanks Jesse, I didn't realise @Exclude can be used class-wide. This is exactly what I was after!

              – Lewsmith
              Nov 20 '18 at 0:50






            • 1





              @Lewsmith No problem! Glad I could help out. Thanks a lot for sharing the full implementation of the interceptor too that looks like a great solution! Might even steal it for a future Nest app :P

              – Jesse Carter
              Nov 20 '18 at 1:51














            3












            3








            3







            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






            share|improve this answer













            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







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 19 '18 at 18:34









            Jesse CarterJesse Carter

            9,17133560




            9,17133560













            • Thanks Jesse, I didn't realise @Exclude can be used class-wide. This is exactly what I was after!

              – Lewsmith
              Nov 20 '18 at 0:50






            • 1





              @Lewsmith No problem! Glad I could help out. Thanks a lot for sharing the full implementation of the interceptor too that looks like a great solution! Might even steal it for a future Nest app :P

              – Jesse Carter
              Nov 20 '18 at 1:51



















            • Thanks Jesse, I didn't realise @Exclude can be used class-wide. This is exactly what I was after!

              – Lewsmith
              Nov 20 '18 at 0:50






            • 1





              @Lewsmith No problem! Glad I could help out. Thanks a lot for sharing the full implementation of the interceptor too that looks like a great solution! Might even steal it for a future Nest app :P

              – Jesse Carter
              Nov 20 '18 at 1:51

















            Thanks Jesse, I didn't realise @Exclude can be used class-wide. This is exactly what I was after!

            – Lewsmith
            Nov 20 '18 at 0:50





            Thanks Jesse, I didn't realise @Exclude can be used class-wide. This is exactly what I was after!

            – Lewsmith
            Nov 20 '18 at 0:50




            1




            1





            @Lewsmith No problem! Glad I could help out. Thanks a lot for sharing the full implementation of the interceptor too that looks like a great solution! Might even steal it for a future Nest app :P

            – Jesse Carter
            Nov 20 '18 at 1:51





            @Lewsmith No problem! Glad I could help out. Thanks a lot for sharing the full implementation of the interceptor too that looks like a great solution! Might even steal it for a future Nest app :P

            – Jesse Carter
            Nov 20 '18 at 1:51













            2














            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.






            share|improve this answer




























              2














              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.






              share|improve this answer


























                2












                2








                2







                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.






                share|improve this answer













                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.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 20 '18 at 1:35









                LewsmithLewsmith

                458




                458






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53378667%2fcast-entity-to-dto%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    How to send String Array data to Server using php in android

                    Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

                    Is anime1.com a legal site for watching anime?