Search code examples
node.jstypescriptnestjstypeorm

How to exclude entity field from returned by controller JSON. NestJS + Typeorm


I want to exclude password field from returned JSON. I am using NestJS and Typeorm.

The solution provided on this question doesn't work for me or in NestJS. I can post my code if needed. Any other ideas or solutions? Thanks.


Solution

  • I'd suggest creating an interceptor that takes advantage of the class-transformer library:

    @Injectable()
    export class TransformInterceptor implements NestInterceptor {
      intercept(
        context: ExecutionContext,
        call$: Observable<any>,
      ): Observable<any> {
        return call$.pipe(map(data => classToPlain(data)));
      }
    }
    

    Then, simply exclude properties using @Exclude() decorator, for example:

    import { Exclude } from 'class-transformer';
    
    export class User {
        id: number;
        email: string;
    
        @Exclude()
        password: string;
    }