gpt4 book ai didi

typescript - NestJS - 避免返回用户密码

转载 作者:行者123 更新时间:2023-12-02 02:15:26 24 4
gpt4 key购买 nike

我在使用 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": "Cannot return null for non-nullable field User._id."

最佳答案

您应该简单地从 password 属性中删除 @Field 装饰器。

// @Field(() => String, { nullable: false })
@Prop({ type: String, required: true, trim: true, minlength: 6 })
password: string;

关于typescript - NestJS - 避免返回用户密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67245560/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com