LoginSignup
0
1

More than 1 year has passed since last update.

GraphQL サーバー構築(その5. GraphQL Code Generator)

Posted at

id: 4f38f3f8

前回

今回やること

  • GraphQL Code Generatorによる型定義ファイルの生成
  • 生成した型定義ファイルをresolverへ適用

GraphQL Code Generatorによる型定義ファイルの生成

bash
--save-dev @graphql-codegen/cli @graphql-codegen/introspection @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-resolvers
  • 下記を追加
package.json
"scripts": {
    "codegen": "gql-gen --watch",
  • codegen.yml を作成
codegen.yml
overwrite: true
# スキーマファイルのパス
schema: src/typedefs/*graphql 
generates:
  # 生成する型定義ファイルのパス
  src/generated/graphql.ts:
    plugins:
      - "typescript"
      - "typescript-resolvers"
  ./graphql.schema.json:
    plugins:
      - "introspection"
bash
$ npm run codegen
  • src/generated/graphql.tsが生成される

image.png

生成した型定義ファイルをresolverへ適用

index.ts
import type { Resolvers } from "./generated/graphql"
const resolvers: Resolvers = {
  Query: {
    books: () => books,
  },
  Mutation: {
    addBook(parent, args) {
      const book = {
        author: args.author,
        title: args.title,
      };
      books.push(book)
      return book;
    }
  }
};
0
1
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
0
1