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.
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.
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;
}
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']
})
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.