10
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

NestJS、GraphQL、type-garphqlでの"Cannot return null for non-nullable field"エラーを解決する

Last updated at Posted at 2020-02-01

Nest.jsを利用してGraphQLをコードファーストアプローチで書いています。

公式ドキュメントに方法が書かれていないのですが、普通にドキュメントの内容に従うと、queryを要求した際にEntityがない場合、エラーが発生してしまいます。

実際のコードを例にあげると以下の通りです。

team.resolver.ts
@Resolver(of => Team)
export class TeamResolver {
  constructor(
    private readonly teamService: TeamService,
    private readonly memberService: MemberService,
  ) {}

  @Query(returns => Team, { name: 'team' })
  @UseGuards(GqlAuthGuard)
  async get(@Args('id') id: string) {
    return this.teamService.findOne(id);
  }
...
}

playgroundでの実行結果(teamが存在しない場合):

Screen Shot 2020-02-01 at 16.43.33.png

このように、"Cannot return null for non-nullable field Query.team."というエラーが帰ってきてしまいます。

これを解決する方法ですが、とてもシンプルで、@Queryデコレーターに{ nullable: true }オプションを追加するだけでOKです。(なぜかNestjsの公式ドキュメントに記述はない)

team.service.ts
@Resolver(of => Team)
export class TeamResolver {
  constructor(...){}

  @Query(returns => Team, { name: 'team', nullable: true }) // nullable: trueを追加
  @UseGuards(GqlA uthGuard)
  async get(@Args('id') id: string) {
    return this.teamService.findOne(id);
  }
...
}

そうすると、teamが見つからなかった場合でもちゃんとnullが返ってきます。

Screen Shot 2020-02-01 at 16.13.21.png

同じようなエラーに悩まされている方の参考になれば嬉しいです。

10
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?