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:

  1. Locate the corresponding interface on the interface management platform
  2. Put the interface’sschemaCopied to thequerier.graphqlormutations.graphqlIn the
  3. performyarn codegen, will automatically generatereact hooksStyle 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-generatorAutomatically generated files.

So let’s take a look at thatgraphql.tsxPart of the code inYou can see,hooksThe call method is neat because it needs to be definedgqlIt’s automatically generated for us, and it’s defineduseAuthorQuery hook. And it’s automatically generatedAuthor typeType.

We summarized several advantages of using GraphQL-code-Generator:

  • I don’t need to define itgql, the code is more concise
  • Direct use ofhooksThe code is more elegant
  • Automatically generateTypescriptType, 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 (trueBy default)schema(required)– toGraphQLSchema, you can use the local file path, URL, etcdocuments– To youGraphQLDocuments: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

6. Generated GraphQL complete code