[英]Type Graphql custom Resolver
Iam have a User ObjectType and want in my LoginResolver, to return the user and a generated token for that user as an Object like so: Iam 有一个用户 ObjectType,并希望在我的 LoginResolver 中,以 Object 的形式返回用户和为该用户生成的令牌,如下所示:
{user:User, token:string}
Currently I can return either the User OR a string, depending on the Type i give in the @Mutation() decorator {user:User, token:string}
目前我可以返回用户或字符串,这取决于我在 @Mutation() 装饰器中给出的类型
@Mutation((returns) => User)
async login(
@Arg("email") email: string,
@Arg("password") password: string,
@Ctx("ctx") ctx: IContext
) {
const user = await this.userRepo.findOneUser({ where: { email } });
const success = await compare(password, user.password);
if (!success) ctx.throw(401);
const token = await this.tokenRepo.createToken(user);
return user;
}
when i try creating an UserWIthToken Objecttype I get the following Error for every field on the user entity:当我尝试创建一个 UserWIthToken 对象类型时,用户实体上的每个字段都会出现以下错误:
app_1 | error: [ValidationError: Cannot query field "id" on type "UserWithToken".] {
app_1 | locations: [ [Object] ],
app_1 | path: undefined,
app_1 | extensions: { code: 'GRAPHQL_VALIDATION_FAILED', exception: [Object] }
app_1 | }
app_1 | }```
dont mind the app_1 here, Iam using docker
You need to create a custom ObjectType for this case您需要为这种情况创建一个自定义 ObjectType
@ObjectType()
class UserWithToken {
@Field(() => User)
user: User
@Field()
token: string
}
Then use that object in your query instead of user然后在查询中使用 object 而不是用户
@Query((returns) => UserWithToken)
async login(
@Arg("email") email: string,
@Arg("password") password: string,
@Ctx("ctx") ctx: IContext
) : Promise<UserWithToken> {
const user = await this.userRepo.findOneUser({ where: { email } });
const success = await compare(password, user.password);
if (!success) ctx.throw(401);
const token = await this.tokenRepo.createToken(user);
return {
user,
token
};
}
Please note I used @Query
here instead of @Mutation
as it fit this case better, as a rule of thumb if you want to read data without modifying it, use Query, other wise for deleting/adding/editing data use Mutation.请注意,我在这里使用了
@Query
而不是@Mutation
,因为它更适合这种情况,根据经验,如果您想在不修改数据的情况下读取数据,请使用 Query,否则删除/添加/编辑数据使用 Mutation。
Then you can run the login query like this然后你可以像这样运行登录查询
query {
login(email: "xx@xx.com", password: "xxxxx") {
token
user {
id
name
email
...
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.