How to exclude entity field from returned by contr

2019-07-11 06:17发布

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.

3条回答
聊天终结者
2楼-- · 2019-07-11 06:32

You can use the package https://github.com/typestack/class-transformer

You can exclude a properties using decorators and also, you can exlude properties using groups.

查看更多
Anthone
3楼-- · 2019-07-11 06:40

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;
}
查看更多
Summer. ? 凉城
4楼-- · 2019-07-11 06:45

As an addition to Kamil's answer:

Instead of creating your own interceptor, you can now use the built-in ClassSerializerInterceptor, see the serialization docs.

@UseInterceptors(ClassSerializerInterceptor)

You can use it on a controller class or its individual methods. Each entity returned by such a method will be transformed with class-transformer.


You can customize its behavior by defining @SerializeOptions() on your controller or its methods:

@SerializeOptions({
  excludePrefixes: ['_'],
  groups: ['admin']
})
查看更多
登录 后发表回答