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:
-
Add the following dev dependencies to your app's
package.jsonfile, then install them with thenpm installcommand.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" -
Enable fetching of GraphQL introspection data by adding the following example script to the
/scripts/fetch-graphql-introspection-data.tsfile:RequestResponseimport { 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. -
To import
scConfigproperly in the above script, add the following extension in thetsconfig.scripts.jsonfile:RequestResponse{ "extends": "./tsconfig.json", "ts-node": { "require": [ "tsconfig-paths/register" ] }, "compilerOptions": { "module": "commonjs" } } -
Add the following script in the
scriptssection of your application's package.json file:RequestResponse"graphql:update": "ts-node --project tsconfig.scripts.json ./scripts/fetch-graphql-introspection-data.ts" -
Configure
graphql-codegenby creating agraphql-codegen.ymlat the root of your app containing the following:RequestResponseoverwrite: 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 -
Run the following command to generate the
src/temp/graphql-types.tsfile containing the necessary types.RequestResponsenpx graphql-codegen --config graphql-codegen.yml