【发布时间】:2021-07-18 13:59:24
【问题描述】:
我的项目使用 GraphQL 和 Mongoose(代码优先方法)时遇到了一点问题。我的用户解析器中有一个 findCurrentUser 查询,它返回有关当前经过身份验证的用户的信息,但我不想返回用户的密码,我该如何避免这种情况?
用户的解析器:
@Query(() => User)
@UseGuards(GqlAuthGuard)
async findCurrentUser(@CurrentUser() user: JwtPayload): Promise<User> {
return await this.usersService.findCurrent(user.id);
}
用户服务:
async findCurrent(id: string): Promise<User> {
try {
// find the user
const user = await this.userModel.findOne({ _id: id });
// if the user does not exists throw an error
if (!user) {
throw new BadRequestException('User not found');
}
// we should not return the user's password
// TODO: this is a temporary solution, needs to be improved
user.password = '';
return user;
} catch (error) {
throw new InternalServerErrorException(error.message);
}
}
用户实体:
import { ObjectType, Field, ID } from '@nestjs/graphql';
import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
import { Document, Schema as MongooseSchema } from 'mongoose';
import { nanoid } from 'nanoid';
@Schema()
@ObjectType()
export class User {
@Field(() => ID)
_id: MongooseSchema.Types.ObjectId;
@Field(() => String, { nullable: false })
@Prop({ type: String, required: true, trim: true })
firstName: string;
@Field(() => String, { nullable: true })
@Prop({ type: String, required: false, trim: true })
lastName?: string;
@Field(() => String, { nullable: true })
@Prop({ type: String, required: false, default: nanoid(10) })
username: string;
@Field(() => String, { nullable: false })
@Prop({
type: String,
unique: true,
required: true,
lowercase: true,
trim: true
})
email: string;
@Field(() => String, { nullable: false })
@Prop({ type: String, required: true, trim: true, minlength: 6 })
password: string;
@Field(() => Boolean, { defaultValue: true })
@Prop({ type: Boolean, default: true })
isActive: boolean;
@Field(() => Date, { defaultValue: Date.now() })
@Prop({ type: Date, default: Date.now() })
createdAt: Date;
}
export type UserDocument = User & Document;
export const UserSchema = SchemaFactory.createForClass(User);
在文档中,NestJS 团队提到了“序列化”,但我已经尝试过但没有成功。我在 GraphQL Playground 上收到以下错误:
"message": "不能为不可为空的字段 User._id 返回 null。"
【问题讨论】:
标签: typescript mongoose graphql nestjs