nullable array of nullable values in nestjs code first graphql
Asked Answered
C

1

5

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

Chapbook answered 18/6, 2021 at 1:47 Comment(0)
H
14

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.

Hyacinthie answered 18/6, 2021 at 1:59 Comment(4)
Hehe, shame on me. It's clear in the docs. I guess I was a little too lazy. I hope the wording of the question helps other lazy people in the future :) – Chapbook
As a lazy person that found this helpful, thank you! πŸŽ‰ – Old
@Jay do have any idea about nullable just List? I want my list to be nullable but not its items. – Genarogendarme
@Genarogendarme probably it's better to return an empty array instead of null – Gaudreau

© 2022 - 2024 β€” McMap. All rights reserved.