Search code examples
node.jstypescriptgraphqltypegraphql

How to define object types with type-graphql


My resolver:

@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
        };
    }
}

And object type:

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

@ObjectType()
class LoginObject {

  @Field()
  user: User;

  @Field()
  accessToken: string;

}

The error I get is - Error: Cannot determine GraphQL output type for 'user' of 'LoginObject' class. Does the value used as its TS type or explicit type is decorated with a proper decorator or is it a proper output value?

How do I make it work?


Solution

  • Since every complex type exposed by the graphql API must be a known type. In your example, LoginObject exposes a complex property type of User so the User class should be annotated with @ObjectType() decorator.