### Configure Codegen with Custom Example API Preset Source: https://github.com/shopify/graphql-codegen/blob/main/README.md Example configuration file demonstrating how to use a custom preset ('example-api/preset') for GraphQL Codegen. This setup automatically includes the schema and type paths defined in the preset. Dependencies include 'example-api/preset'. ```typescript // /codegen.ts // This uses @shopify/graphql-codegen internally: import {preset, pluckConfig} from 'example-api/preset'; export default { overwrite: true, pluckConfig, generates: { 'example-api.generated.d.ts': { preset, documents: ['**/*.ts'], }, }, }; ``` -------------------------------- ### Custom API Preset Wrapper for GraphQL Codegen Source: https://context7.com/shopify/graphql-codegen/llms.txt This example illustrates how to create a reusable preset wrapper for a specific API, pre-configuring schema paths and types. It simplifies consumer configuration by abstracting common settings into a custom preset. ```typescript // example-api/preset.ts import {preset as internalPreset} from '@shopify/graphql-codegen'; export {pluckConfig} from '@shopify/graphql-codegen'; // Export custom preset with API-specific defaults export const preset = { buildGeneratesSection: (options) => { return internalPreset.buildGeneratesSection({ ...options, // Known schema path from the package schema: 'example-api/schema.json', presetConfig: { importTypes: { namespace: 'ExampleAPI', from: 'example-api/types', }, interfaceExtension: ({queryType, mutationType}) => ` declare module 'example-api/client' { interface ExampleQueries extends ${queryType} {} interface ExampleMutations extends ${mutationType} {} } `, ...options.presetConfig, }, }); }, }; // Consumer configuration becomes simpler // codegen.ts import {preset, pluckConfig} from 'example-api/preset'; export default { overwrite: true, pluckConfig, generates: { 'example-api.generated.d.ts': { preset, documents: ['**/*.ts'], }, }, }; ``` -------------------------------- ### Implement Type-Safe GraphQL Mutations with Variables Source: https://context7.com/shopify/graphql-codegen/llms.txt Demonstrates a type-safe client function for making GraphQL mutations with support for required and optional variables. It includes an example of defining mutation interfaces, calling the client function, and handling the typed response. ```typescript // my-api-client.ts export interface MyAPIMutations {} export async function clientMutation< OverrideReturnType extends any = never, RawGqlString extends string = string, >( mutation: RawGqlString, ...params: ClientVariablesInRestParams ): Promise> { const {variables} = params[0] ?? {}; const response = await fetch('https://my-api.com/graphql', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({query: mutation, variables}), }); return response.json(); } // Usage with required variables const result = await clientMutation(`#graphql mutation createProduct($input: ProductInput!) { productCreate(input: $input) { product { id title } userErrors { field message } } } `, { variables: { input: { title: 'New Product', productType: 'Widget', } } }); // Type-safe access to mutation result if (result.productCreate.userErrors.length > 0) { console.error('Errors:', result.productCreate.userErrors); } else { console.log('Created:', result.productCreate.product.id); } ``` -------------------------------- ### Define Custom GraphQL Codegen Preset for Example API Source: https://github.com/shopify/graphql-codegen/blob/main/README.md A custom preset that wraps '@shopify/graphql-codegen's preset, providing default values for schema path and type imports. This simplifies configuration for a specific API. Dependencies include '@shopify/graphql-codegen'. ```typescript // example-api/preset.ts import {preset as internalPreset} from '@shopify/graphql-codegen'; export {pluckConfig} from '@shopify/graphql-codegen'; // Export a custom preset that adds default values to @shopify/graphql-codegen: export const preset = { buildGeneratesSection: (options) => { return internalPreset.buildGeneratesSection({ ...options, // Known schema path from the example-api package: schema: 'example-api/schema.json' presetConfig: { importTypes: { namespace: 'ExampleAPI', // Known types path from the example-api package: from: 'example-api/types', }, interfaceExtension: ({queryType, mutationType}) => ` declare module 'example-api/client' { interface AdminQueries extends ${queryType} {} interface AdminMutations extends ${mutationType} {} }`, }, }); }, }; ``` -------------------------------- ### Implement Type-Safe GraphQL Client (TypeScript) Source: https://context7.com/shopify/graphql-codegen/llms.txt This TypeScript code demonstrates how to create a type-safe GraphQL client using utility types from the '@shopify/graphql-codegen' package. It ensures proper type inference for queries and variables, and includes examples of basic usage, variable usage, and overriding return types. ```typescript import type { ClientReturn, ClientVariablesInRestParams, } from '@shopify/graphql-codegen'; // Empty interface extended by generated types in user projects export interface MyAPIQueries {} export interface MyAPIMutations {} export async function clientQuery< OverrideReturnType extends any = never, RawGqlString extends string = string, >( query: RawGqlString, ...params: ClientVariablesInRestParams ): Promise> { // params and params.variables are optional if query has no variables const {variables} = params[0] ?? {}; // Client implementation - can forward to Apollo, urql, etc. const response = await fetch('https://my-api.com/graphql', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({query, variables}), }); const data = await response.json(); if (data.errors) { throw new Error(data.errors[0].message); } return data.data; } // Usage with inferred types const result = await clientQuery(`#graphql query layout { shop { name description } } `); // result.shop.name is typed as string // Usage with variables - params become required const product = await clientQuery(`#graphql query product($id: ID!) { product(id: $id) { title price } } `, { variables: { id: '123' } }); // Override return type when needed const custom = await clientQuery<{shop: {customField: string}}> `query { shop { name } }` ); ``` -------------------------------- ### Generated TypeScript types for GraphQL query Source: https://github.com/shopify/graphql-codegen/blob/main/README.md An example of the `d.ts` file generated by the Shopify GraphQL Codegen. It includes type definitions for query variables and the query result, along with interface extensions for integrating with a custom GraphQL client, demonstrating the output of the codegen process. ```typescript // my-api.generated.d.ts import type * as MyAPI from 'path/to/my-api-types'; export type LayoutQueryVariables = MyAPI.Exact<{[key: string]: never}>; export type LayoutQuery = { shop: Pick; }; interface GeneratedQueryTypes { '#graphql\n query layout {\n shop {\n name\n description\n }\n }\n': { return: LayoutQuery; variables: LayoutQueryVariables; }; } interface GeneratedMutationTypes {} declare module 'my-api-client' { interface MyAPIQueries extends GeneratedQueryTypes {} interface MyAPIMutations extends GeneratedMutationTypes {} } ``` -------------------------------- ### Custom GraphQL Client with Variables and Options Source: https://context7.com/shopify/graphql-codegen/llms.txt An advanced example of a custom GraphQL client that supports additional options like caching and debugging, along with auto-injected variables such as locale and currency. It showcases how to define custom client options and integrate them into the client's fetch logic. ```typescript import type { ClientReturn, ClientVariablesInRestParams, } from '@shopify/graphql-codegen'; interface MyAPIQueries {} // Client with additional options like caching and debugging type ClientOptions = { cache?: 'no-cache' | 'force-cache'; debug?: boolean; }; // Auto-injected variables that client adds automatically type AutoInjectedVars = 'locale' | 'currency'; export async function clientQuery< OverrideReturnType extends any = never, RawGqlString extends string = string, >( query: RawGqlString, ...params: ClientVariablesInRestParams< MyAPIQueries, RawGqlString, ClientOptions, AutoInjectedVars > ): Promise> { const options = params[0] ?? {}; const variables = { ...options.variables, // Auto-inject variables locale: 'en-US', currency: 'USD', }; if (options.debug) { console.log('Query:', query); console.log('Variables:', variables); } const response = await fetch('https://my-api.com/graphql', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({query, variables}), cache: options.cache, }); return response.json(); } // Usage with custom options const result = await clientQuery( `query product($id: ID!) { product(id: $id) { title } }`, { variables: { id: '123' }, cache: 'no-cache', debug: true, } ); ``` -------------------------------- ### Generate Enums with GraphQL Codegen by Using .ts Extension Source: https://context7.com/shopify/graphql-codegen/llms.txt Shows how to configure GraphQL Codegen to generate enums instead of union types by specifying a `.ts` extension for the output file. It includes the configuration and an example of a generated enum and its usage in code. ```typescript // codegen.ts export default { overwrite: true, pluckConfig, generates: { // Use .ts extension to generate enums 'api.generated.ts': { preset, schema: './schema.graphql', documents: ['./src/**/*.ts'], presetConfig: { interfaceExtension: ({queryType, mutationType}) => ` declare module './client' { interface Queries extends ${queryType} {} interface Mutations extends ${mutationType} {} } `, }, }, }, }; // Generated file will contain enums instead of union types // api.generated.ts export enum ProductStatus { ACTIVE = 'ACTIVE', ARCHIVED = 'ARCHIVED', DRAFT = 'DRAFT' } // Usage in code const status: ProductStatus = ProductStatus.ACTIVE; ``` -------------------------------- ### GraphQL CLI Codegen Configuration in TypeScript Source: https://github.com/shopify/graphql-codegen/blob/main/README.md Provides a sample configuration file (`codegen.ts`) for the GraphQL CLI. This configuration sets up the plugin and preset for generating TypeScript types, specifying schema, documents, and custom presets options like `importTypes`, `skipTypenameInOperations`, and `interfaceExtension`. ```typescript // /codegen.ts import type {CodegenConfig} from '@graphql-codegen/cli'; import {pluckConfig, preset} from '@shopify/graphql-codegen'; export default { overwrite: true, pluckConfig, generates: { 'my-api.generated.d.ts': { preset, schema: './path/to/my-api-schema.json', documents: ['./src/graphql/my-api/*.{ts,tsx,js,jsx}'], presetConfig: { // Generate the line `import type * as MyAPI from 'path/to/my-api-types';`. // If you don't have generated types for your API beforehand, // omit this parameter to generate the types inline. importTypes: { namespace: 'MyAPI', from: 'path/to/my-api-types', }, // Skip the __typename property from generated types: skipTypenameInOperations: true, // Add a custom interface extension to connect // the generated types to the GraphQL client: interfaceExtension: ({queryType, mutationType}) => ` declare module 'my-api-client' { interface MyAPIQueries extends ${queryType} {} interface MyAPIMutations extends ${mutationType} {} } `, }, }, }, } as CodegenConfig; ``` -------------------------------- ### Configure Shopify GraphQL Codegen Preset (TypeScript) Source: https://context7.com/shopify/graphql-codegen/llms.txt This configuration sets up the Shopify GraphQL Codegen preset for the GraphQL CLI. It specifies the output file, schema location, document paths, and preset configurations for importing types, skipping __typename, and extending client interfaces. ```typescript import type {CodegenConfig} from '@graphql-codegen/cli'; import {pluckConfig, preset} from '@shopify/graphql-codegen'; export default { overwrite: true, pluckConfig, generates: { 'my-api.generated.d.ts': { preset, schema: './path/to/my-api-schema.json', documents: ['./src/graphql/my-api/*.{ts,tsx,js,jsx}'], presetConfig: { // Import pre-generated types for the API importTypes: { namespace: 'MyAPI', from: 'path/to/my-api-types', }, // Remove __typename from generated operation types skipTypenameInOperations: true, // Connect generated types to the GraphQL client interfaceExtension: ({queryType, mutationType}) => ` declare module 'my-api-client' { interface MyAPIQueries extends ${queryType} {} interface MyAPIMutations extends ${mutationType} {} } `, }, }, }, } as CodegenConfig; ``` -------------------------------- ### TypeScript GraphQL Client with Error Handling Source: https://context7.com/shopify/graphql-codegen/llms.txt Implements a type-safe GraphQL client function in TypeScript that fetches data from a GraphQL endpoint, validates the HTTP response, and handles potential GraphQL errors. It uses `fetch` for network requests and defines custom types for GraphQL responses. Dependencies include `@shopify/graphql-codegen` for utility types. ```typescript import type { ClientReturn, ClientVariablesInRestParams, } from '@shopify/graphql-codegen'; export interface MyAPIQueries {} type GraphQLResponse = { data?: T; errors?: Array<{ message: string; locations?: Array<{line: number; column: number}>; path?: string[]; extensions?: Record; }>; }; export async function clientQuery< OverrideReturnType extends any = never, RawGqlString extends string = string, >( query: RawGqlString, ...params: ClientVariablesInRestParams ): Promise> { const {variables} = params[0] ?? {}; let response: Response; try { response = await fetch('https://my-api.com/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }, body: JSON.stringify({query, variables}), }); } catch (error) { throw new Error(`Network error: ${error.message}`); } if (!response.ok) { throw new Error(`HTTP error ${response.status}: ${response.statusText}`); } const json: GraphQLResponse = await response.json(); if (json.errors && json.errors.length > 0) { const error = json.errors[0]; const message = `GraphQL error: ${error.message}`; const details = error.path ? ` at path: ${error.path.join('.')}` : ''; throw new Error(message + details); } if (!json.data) { throw new Error('No data returned from GraphQL API'); } return json.data; } // Usage with error handling try { const result = await clientQuery(`#graphql query shop { shop { name } } `); console.log(result.shop.name); } catch (error) { console.error('Query failed:', error.message); } ``` -------------------------------- ### Inferring types with clientQuery in TypeScript Source: https://github.com/shopify/graphql-codegen/blob/main/README.md Demonstrates how to use the `clientQuery` function to execute a GraphQL query and how TypeScript infers the type of the `shop` object based on the query structure. This showcases the type generation capabilities. ```typescript // `shop` is inferred as {name: string, description: string} const {shop} = await clientQuery(`#graphql query layout { shop { name description } } `); ``` -------------------------------- ### GraphQL Fragment Composition with String Interpolation Source: https://context7.com/shopify/graphql-codegen/llms.txt Demonstrates how to handle GraphQL fragments and query composition using template literals with type inference. The 'as const' assertion is crucial for ensuring proper type inference when interpolating fragments into queries. ```typescript // Using fragments with string interpolation const fragment = `#graphql fragment ShopInfo on Shop { name description email } ` as const; // 'as const' required for string interpolation const query = `#graphql ${fragment} query layout { shop { ...ShopInfo primaryDomain { url } } } ` as const; // 'as const' ensures proper type inference const result = await clientQuery(query); // result.shop has all fragment fields typed correctly console.log(result.shop.name, result.shop.email); ``` -------------------------------- ### Create Type-Safe GraphQL Client with @shopify/graphql-codegen Source: https://github.com/shopify/graphql-codegen/blob/main/README.md Utility types for creating a GraphQL client that infers response and variable types from query strings. It supports optional return type overrides and automatic variable injection. Dependencies include '@shopify/graphql-codegen'. ```typescript // my-api-client.ts import type { ClientReturn, ClientVariablesInRestParams, } from '@shopify/graphql-codegen'; // Empty interface to be extended with the generated queries and mutations in user projects. export interface MyAPIQueries {} export async function clientQuery< OverrideReturnType extends any = never, RawGqlString extends string = string, >( query: RawGqlString, ...params: ClientVariablesInRestParams ): Promise> { // The 'params' and 'params.variables' are optional // if the query has no variables, required otherwise. const {variables} = params[0] ?? {}; // Client implementation (this could be forwarding the query to Apollo, urql, useQuery, etc.) const response = await fetch('https://my-api.com/graphql', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({query, variables}), }); return response.json(); } // Example usage: // data = await clientQuery('query layout {shop {name}}'); // data = await clientQuery<{shop: {name: string}}>('...'); /* Type utility details: ClientVariablesInRestParams< MyAPIQueries, RawGqlString, AdditionalParamOptions, AutoInjectedVariables >; */ ``` -------------------------------- ### Using Generated Types in Components with TypeScript Source: https://context7.com/shopify/graphql-codegen/llms.txt This snippet shows how to import and use generated query types for component props, ensuring full type safety. It demonstrates type inference for query results and how TypeScript catches errors for undefined properties. ```typescript // Layout.tsx import {clientQuery} from './my-api-client'; import type {LayoutQuery} from './my-api.generated'; // Query with inferred return type const {shop} = await clientQuery(`#graphql query layout { shop { name description } } `); // shop is typed as {name: string, description: string} console.log(shop.name, shop.description); // Component using the generated type export function Layout({shop}: LayoutQuery) { return (

{shop.name}

{shop.description}

); } // TypeScript will error on undefined properties // shop.notDefined; // Error: Property 'notDefined' does not exist ``` -------------------------------- ### Using `as const` for string interpolation in GraphQL queries Source: https://github.com/shopify/graphql-codegen/blob/main/README.md Illustrates the correct way to handle string interpolation for GraphQL queries when they are built using template literals. Adding `as const` ensures that the string literal type is preserved, preventing generic `string` assignment and potential type conflicts. ```typescript const fragment = `#graphql fragment MyFragment on Shop { name description } `; const query = `#graphql ${fragment} query layout { shop { ...MyFragment } } ` as const; // <--- Add `as const` here ``` -------------------------------- ### Configure Inline Type Generation with GraphQL Codegen Source: https://context7.com/shopify/graphql-codegen/llms.txt Configures GraphQL Codegen to generate types inline within a .d.ts file, avoiding external type imports. It sets up schema and document paths and customizes the preset configuration to skip typename in operations and extend client interfaces. ```typescript // codegen.ts import type {CodegenConfig} from '@graphql-codegen/cli'; import {pluckConfig, preset} from '@shopify/graphql-codegen'; export default { overwrite: true, pluckConfig, generates: { 'api.generated.d.ts': { preset, schema: './schema.graphql', documents: ['./src/**/*.{ts,tsx}'], presetConfig: { // Omit importTypes to generate types inline // All schema types will be generated in the output file skipTypenameInOperations: true, interfaceExtension: ({queryType, mutationType}) => ` declare module './client' { interface Queries extends ${queryType} {} interface Mutations extends ${mutationType} {} } `, }, }, }, } as CodegenConfig; ``` -------------------------------- ### Importing generated types in React component Source: https://github.com/shopify/graphql-codegen/blob/main/README.md Shows how to import generated types from a `.d.ts` file into a React component to explicitly declare the expected shape of the data received from a GraphQL query. This enhances type safety and developer experience. ```tsx import type {LayoutQuery} from './my-api.generated'; export function Layout({shop}: LayoutQuery) { return (

{shop.name}

{shop.description}

); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.