首页 > 解决方案 > 如何使用 type-graphql 定义对象类型

问题描述

我的解析器:

@Resolver()
class UserResolver{
    @Query(()  => Boolean)
    async userExists(@Arg('email') email: string) {
        const user = await User.findOne({email});
        return user ? true : false;
    }

    @Mutation(() => LoginObject)
    async login(
        @Arg('email') email: string,
        @Arg('password') password: string
    ): Promise<LoginObject>{

        const user = await User.findOne({email});
        if(!user) throw new Error('User not found!');
        const match = await cmp(password, user.password);
        if(!match) throw new Error('Passwords do not match!');
        return {
            accessToken: createAccessToken(user),
            user
        };
    }
}

和对象类型:

import {ObjectType, Field} from "type-graphql";
import User from "../entity/User";

@ObjectType()
class LoginObject {

  @Field()
  user: User;

  @Field()
  accessToken: string;

}

我得到的错误是 - 错误:无法确定“LoginObject”类的“用户”的 GraphQL 输出类型。用作其 TS 类型或显式类型的值是用适当的装饰器装饰的还是适当的输出值?

我如何使它工作?

标签: node.jstypescriptgraphqltypegraphql

解决方案


由于 graphql API 公开的每个复杂类型都必须是已知类型。在您的示例中,LoginObject公开了一个复杂的属性类型,User因此User该类应使用@ObjectType()装饰器进行注释。


推荐阅读