preface
The GraphQL interface is used in the company, and there is a corresponding interface management platform. At work, the interface is called as follows:
- Locate the corresponding interface on the interface management platform
- Put the interface’s
schema
Copied to thequerier.graphql
ormutations.graphql
In the - perform
yarn codegen
, will automatically generatereact hooks
Style code
Calling the GraphQL interface in this way is convenient and elegant in my opinion. The core of this approach is to generate react hooks style code via graphQL-code-generator.
contrast
1. General call method
2. Invoke hooks generated by graphQL-code-generator
Maybe some of you are curious'.. /generated/graphql.tsx'
Where did this file come from? In fact, this isgraphql-code-generator
Automatically generated files.
So let’s take a look at thatgraphql.tsx
Part of the code inYou can see,hooks
The call method is neat because it needs to be definedgql
It’s automatically generated for us, and it’s defineduseAuthorQuery hook
. And it’s automatically generatedAuthor type
Type.
We summarized several advantages of using GraphQL-code-Generator:
- I don’t need to define it
gql
, the code is more concise - Direct use of
hooks
The code is more elegant - Automatically generate
Typescript
Type, the experience is more friendly
In actual combat
Let’s take a look at how graphQL-code-generator is used in a project. React, for example, also supports Vue, Angular, etc.
1. Install the GraphqL-code-generator command line tool
yarn add graphql
yarn add -D @graphql-codegen/cli
Copy the code
Install plugins that generate hooks style
In this step, you can install the plugins for your project
yarn add @graphql-codegen/typescript-react-apollo
yarn add @graphql-codegen/typescript
yarn add @graphql-codegen/typescript-operations
Copy the code
3. Write interfaces that need to be generated in the project
query mutation
4. Write the GraphQL-code-generator configuration file
overwrite
– Flags for overwriting files when generating code (true
By default)schema
(required)– toGraphQLSchema
, you can use the local file path, URL, etcdocuments
– To youGraphQL
Documents:Query, mutation, subscription, fragment
generates
(required)– A map where the key represents the output path of the generated code and the value represents a set of related options for that particular file:
- Generates.plugins (required) – a list of plugins to be used when generating a file
5. Configure package.json scripts
{
"scripts": {
"codegen": "graphql-codegen"
},
}
Copy the code
At this point, the configuration is almost complete. Simply execute YARN CodeGen and the GraphQL code will be generated automatically