GraphQL 服务器构建(第5节 – GraphQL 代码生成器)

id: 4f38f3f8 is translated as
编号:4f38f3f8

上次

 

这次要做的事情

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

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

通过GraphQL Code Generator生成类型定义文件。

(Literal translation:
Generate type definition files using GraphQL Code Generator.)

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

将生成的类型定义文件应用于解析器(resolver)。

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;
    }
  }
};
广告
将在 10 秒后关闭
bannerAds