Search code examples
graphqltypegraphqltypegoose

TypeGraphQL and Typegoose InputType of Ref array


I'm having difficulties to find resources which explains how to cope with array of References to objects with TypeGraphQL and Typegoose.

Given the following models:

@ObjectType({description: "Blog Tag Model"})
export class BlogTag {

  @Field(() => ID)
  id: number;

  @Field(_type => String)
  @Property({required: true, unique: true, index: true, trim: true })
  name: string;
}

@ObjectType({ description: "Blog post model" })
export class BlogPost {

  @Field(() => ID)
  id: number;

  @Field()
  @Property({required: true})
  title: string;

  @Field()
  @Property({required: true})
  description: string;

  @Field(_type => [BlogTag], {nullable: false})
  @Property({default: [], ref: 'BlogTag'})
  tags: Ref<BlogTag>[];
}


@InputType({ description: "Blog post input" })
export class BlogPostInput implements Partial<BlogPost>{

  @Field()
  @Property()
  title: string;

  @Field()
  @Property()
  description: string;

  // Here is the problem / question
  @Field(_type => [BlogTag], {nullable: false})
  @Property({ref: BlogTag})
  tags: Ref<BlogTag>[];   
}

This is the error obtained for this code:

CannotDetermineGraphQLTypeError: Cannot determine GraphQL input type for 'tags' of 'BlogPostInput' class. Is the value, that is used as its TS type or explicit type, decorated with
a proper decorator or is it a proper input value?

What I want to achieve is to give possibility to BlogPost model to store an array of References/ObejctIDs of the BlogTag model.

I am new to this framework and I don't know if this is a good practice. How can I create an InputType which accepts an array of IDs?


Solution

  • You need to create a separate BlogTagInput with @InputType or check the FAQ for some handy yet "doatyourownrisk" workaround:

    https://typegraphql.com/docs/faq.html#situations-frequently-arise-where-inputtype-and-objecttype-have-exactly-the-same-shape-how-can-i-share-the-definitions