【Day 7】建立网络环境 – GraphQL代码生成器

首先

スライド8.PNG

2023年是圣诞降临节历法的第七天。

 

在上一次的基础上,我们将继续推进“开发者可以进行Web开发”的话题。

image.png

GraphQL 代码生成器

GraphQL Code Generator是什么?

 

安装

npm i graphql
npm i -D typescript @graphql-codegen/cli

由于提供了init命令,我将尝试使用它。

npx graphql-code-generator init

    Welcome to GraphQL Code Generator!
    Answer few questions and we will setup everything for you.

? What type of application are you building?
どのアプリケーションを使用していますか?
⇒ Application built with React

? Where is your schema?: (path or url)
Schemaファイルはどこにありますか?
⇒ ./schema.graphql

? Where are your operations and fragments?:
オペレーションやフラグメントはどこにありますか?
⇒ src/graphql/*.graphql

? Where to write the output
アウトプットファイル先はどこにしますか?
⇒ src/graphql/generated.tsx

? Do you want to generate an introspection file?
イントロスペクションファイルを生成しますか?
⇒ No

? How to name the config file? codegen.ts
コンフィグファイルの名前はどうしますか?
⇒ codege.ts(default)

? What script in package.json should run the codegen?
スクリプトの名前はどうしますか?
⇒ codegen
type Blog {
  title: String!
  author: String!
  body: String!
  createdAt: String!
}

type Query {
  blogs: [Blog!]!
}
query GetBlogs {
  blogs {
    ...BlogFields
  }
}

fragment BlogFields on Blog {
  title
  author
  body
  createdAt
}

现在准备工作完成了。

阿波罗客户端

我打算使用Apollo Client从Web上发送请求,所以我会进行相关的设置。

 

npm install @apollo/client
npm install --save-dev @graphql-codegen/typescript-react-apollo
import type { CodegenConfig } from '@graphql-codegen/cli'

const config: CodegenConfig = {
  overwrite: true,
  schema: './schema.graphql',
  documents: 'src/graphql/*.graphql',
  generates: {
    'src/graphql/generated.tsx': {
      plugins: [
        'typescript',
        'typescript-operations',
        'typescript-react-apollo',
      ],
    },
    // mockサーバー側のSchemaファイルを生成
    'mock/schema.graphql': {
      plugins: ['schema-ast'],
    },
  },
}

export default config
npm run codegen

如果文件已经成功生成,那么就完成了。

源代码文件/src/graphqll/generated.tsx:/src/graphqll/generated.tsx文件导入了一些模块,并定义了一些类型以及一些Apollo Client相关的操作。

它包含了一些类型定义,例如Maybe、InputMaybe、Exact、MakeOptional等等。还包含了一个常量defaultOptions,以及一些GraphQL类型定义。

还定义了Blog和Query类型,以及GetBlogsQueryVariables和GetBlogsQuery类型。

文件中还定义了一些使用GraphQL的操作,例如useGetBlogsQuery、useGetBlogsLazyQuery和useGetBlogsSuspenseQuery等。

文件最后导出了一些类型和函数。

/src/graphqll/generated.tsx文件的内容基本上是关于GraphQL操作和类型定义的相关内容。

现在可以进行Web开发了。

image.png

从下一次开始,我们将进入制作首页的阶段。

image.png