Implement GraphQL code generation

GraphQL code generation automatically creates strongly typed code based on your schema and operations. It generates type-safe code artifacts using the graphql-codegen package, ensuring consistency between the front-end implementation and the underlying GraphQL API.

You can follow this topic to manually implement GraphQL code generation in your app using the graphql-codegen package.

To implement GraphQL code generation:

  1. Add the following dev dependencies to your app's package.json file, then install them with the npm install command.

    RequestResponse
    "graphql": "^16.11.0",
    "graphql-tag": "^2.12.6",
    "@graphql-codegen/cli": "^5.0.7",
    "@graphql-codegen/typescript": "^4.1.6",
    "@graphql-codegen/typescript-operations": "^4.6.1",
    "@graphql-codegen/typescript-react-query": "^6.1.1"
    "ts-node": "^10.9.1",
    "tsconfig-paths": "^4.1.2",
    "dotenv": "^16.5.0"
  2. Enable fetching of GraphQL introspection data by adding the following example script to the /scripts/fetch-graphql-introspection-data.ts file:

    RequestResponse
    import { GraphQLRequestClient } from "@sitecore-content-sdk/nextjs/client";
    import fs from "fs";
    import { getIntrospectionQuery } from "graphql";
    // Load environment variables using 'dotenv/config' before importing scConfig
    // If for local development you are using `.env.local` you can load it passing its path:
    // require('dotenv').config({ path: '.env.local' });
    import "dotenv/config";
    import scConfig from "sitecore.config";
    
    // construct the GraphQL endpoint URL using edgeUrl and contextId from the config
    const graphQLEndpoint = `${scConfig.api.edge.edgeUrl}/v1/content/api/graphql/v1?sitecoreContextId=${scConfig.api.edge.contextId}`;
    
    const client = new GraphQLRequestClient(graphQLEndpoint);
    
    console.log(
      `Fetch graphql introspection data from ${scConfig.api.edge.edgeUrl}/v1/content/api/graphql/v1 ...`
    );
    
    client
      .request(getIntrospectionQuery())
      .then((result) => {
        fs.writeFile(
          "./.sitecore/GraphQLIntrospectionResult.json",
          JSON.stringify(result, null, 2),
          (err) => {
            if (err) {
              console.error("Error writing GraphQLIntrospectionResult file", err);
              return;
            }
    
            console.log("GraphQL Introspection Data successfully fetched!");
          }
        );
      })
      .catch((e) => {
        console.error(e);
      });
    

    This file fetches the GraphQL introspection data exposed by SItecore instance's GraphQL API and stores it in ./sitecore/GraphQLIntrospectionResult.json. This file is used to generate the TypeScript types.

  3. To import scConfig properly in the above script, add the following extension in the tsconfig.scripts.json file:

    RequestResponse
    {
        "extends": "./tsconfig.json",
        "ts-node": {
            "require": [
                "tsconfig-paths/register"
            ]
        },
        "compilerOptions": {
            "module": "commonjs"
        }
    }
  4. Add the following script in the scripts section of your application's package.json file:

    RequestResponse
    "graphql:update": "ts-node --project tsconfig.scripts.json ./scripts/fetch-graphql-introspection-data.ts"
  5. Configure graphql-codegen by creating a graphql-codegen.yml at the root of your app containing the following:

    RequestResponse
    overwrite: true # Overwrite existing files
    documents: 'src/**/*.graphql' # Adjust the path to your GraphQL documents; remove it if you don't have .graphql files in your solution
    schema: '.sitecore/GraphQLIntrospectionResult.json' # the path to your introspection result file
    generates:
      .sitecore/graphql-types.ts: # The output file for generated types
        plugins:
          - 'typescript' # Generates TypeScript types for GraphQL operations
          - 'typescript-operations' # Generates TypeScript types for GraphQL operations
          - 'typescript-react-query' # Generates React Query hooks for GraphQL operations
    
  6. Run the following command to generate the src/temp/graphql-types.ts file containing the necessary types.

    RequestResponse
    npx graphql-codegen --config graphql-codegen.yml

Do you have some feedback for us?

If you have suggestions for improving this article,