Search code examples
typescriptgraphqltypegraphql

typegraphql delegate query fields to field resolver


I want a user query which delegates it's fields to the field resolvers below. What do I return from the query to allow this behaviour?

@ObjectType()
class User {
  @Field((_type) => ID)
  id!: string;

  @Field((_type) => [View])
  saved!: View[];
}


@Resolver(of => User)
export class UserResolver {
  @Authorized()
  @Query((_returns) => User, { nullable: false })
  async user(@Ctx() { prisma, uid }: context.AuthorizedContext) {
    return {
      id: uid,
    };
  }

  @FieldResolver()
  async saved(
    @Root() { id }: User,
    @Ctx() { prisma }: context.AuthorizedContext
  ) {
    console.log("HELLO")

    const savedViews = await prisma.saved.findMany({
      where: { userId: id },
      include: { View: true },
    });

    return savedViews.map((dboView) => dboView.View);
  }
}

I've tried not returning the fields in the query, but get a Cannot return null for non-nullable field User.saved


Solution

  • Have you tried removing the field declaration from your class? The field resolver is sufficient to add the field to your schema.

    
    @ObjectType()
    class User {
      @Field((_type) => ID)
      id: string;
    }
    

    in your resolver:

    @FieldResolver() // this is sufficient!
      async saved( ... )