所以,我的任务是防止在处理请求后将密码字段发送到响应。为此,我找到了这个拦截器实现
export type ClassConstructor = new (...args: any[]) => object;
export class SerializeInterceptor implements NestInterceptor {
constructor(private dto: ClassConstructor) {}
intercept(context: ExecutionContext, handler: CallHandler): Observable<any> {
return handler.handle().pipe(
map((data: ClassConstructor) => {
return plainToClass(this.dto, data, {
excludeExtraneousValues: true,
exposeUnsetFields: false,
});
}),
);
}
}
现在,为了使用它,我刚刚为其制作了装饰器
export function Serialize(dto: ClassConstructor) {
return UseInterceptors(new SerializeInterceptor(dto));
}
这是在其中一个控制器中使用的示例
@Serialize(LoginResponseDto)
@Post('registration')
registration(@Body() createUserDto: CreateUserDto) {
return this.authService.registration(createUserDto);
}
我用的Dto是这样的
export class UserEntity {
@Expose()
_id: string;
@Expose()
firstName: string;
@Expose()
lastName: string;
@Expose()
email: string;
}
export class LoginResponseDto {
@Expose()
@Type(() => UserEntity)
user: UserEntity;
@Expose()
accessToken: string;
@Expose()
refreshToken: string;
}
所以,问题是当我运行注册或登录时,我不需要返回密码。它有效,现在我没有得到密码,但响应中的 _id 值每次都会改变。 回复正文:
{
"user": {
"_id": "66d8223e932f4803a4d3810e", --wrong _id value
"firstName": "name",
"lastName": "last",
"email": "email"
},
"accessToken": "accessToekn",
"refreshToken": "refreshToken"
}
我需要获取的值:66d81d858c7066f3b63fb21d。 id的变化是因为拦截器中的这个选项:extractExtraneousValues: true, 如果没有它, _id 字段不会改变,但现在我得到这样的响应:
{
"user": {
"$__": {
"activePaths": {
"paths": {
"password": "init",
"email": "init",
"lastName": "init",
"firstName": "init",
"_id": "init",
"__v": "init"
},
"states": {
"require": {},
"init": {
"_id": true,
"firstName": true,
"lastName": true,
"email": true,
"password": true,
"__v": true
}
}
},
"skipId": true
},
"$isNew": false,
"_doc": {
"_id": "66d81d858c7066f3b63fb21d", --doesn't change
"firstName": "first",
"lastName": "last",
"email": "email",
"password": "password",
"__v": 0
},
"_id": "66d81d858c7066f3b63fb21d", --doesn't change
"firstName": "fisrt",
"lastName": "last",
"email": "email"
},
"accessToken": "token",
"refreshToken": "token"
}
也许我需要更改模型中的某些内容?
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument } from 'mongoose';
export type UserDocument = HydratedDocument<User>;
@Schema()
export class User {
@Prop({ required: true })
firstName: string;
@Prop({ required: true })
lastName: string;
@Prop({ required: true, unique: true })
email: string;
@Prop({ required: true })
password: string;
}
export const UserSchema = SchemaFactory.createForClass(User);
我真的迷失了,如果有人有答案,我将不胜感激。
当更改 _id 的标志为 true 时,我尝试将 LoginResopnseD 中的 _id 属性赋予 @Transform(value=>value.obj._id.toString()) ,但它仅有时有效,并且大多数情况下到时候就不会了
您可以尝试使用 SerializeInterceptor 中的 data.toJson() 方法转换 User 模型,让我们看看它是否修复它。