Search code examples
graphqlnestjscode-first

nullable array of nullable values in nestjs code first graphql


How can I get a field of type array that allows nullable values when using the code-first approach in nestjs graphql.

The example shows that

  @Field(type => [String])
  ingredients: string[];

generates [String!]! in the schema.gql file. How can I get just [String]? using {nullable: true} gives me [String!]

I was hoping to find some type of utility or parameter in the @Field decorator, but It seems it isn't


Solution

  • You need to set @Field(() => [String], { nullable: 'itemsAndList' }) as described in the docs

    When the field is an array, we must manually indicate the array type in the Field() decorator's type function, as shown below:

    @Field(type => [Post])
    posts: Post[];
    

    Hint Using array bracket notation ([ ]), we can indicate the depth of the array. For example, using [[Int]] would represent an integer matrix.

    To declare that an array's items (not the array itself) are nullable, set the nullable property to 'items' as shown below:

    @Field(type => [Post], { nullable: 'items' })
    posts: Post[];`
    

    If both the array and its items are nullable, set nullable to 'itemsAndList' instead.