### Run Development Server Source: https://github.com/dotansimha/graphql-code-generator/blob/master/examples/react/apollo-client-swc-plugin/README.md Use this command to start the development server for the Apollo Client Vite SWC plugin example. ```bash pnpm dev ``` -------------------------------- ### Example Urql Client Setup with Persisted Queries Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/presets/preset-client.mdx Configure the Urql client to use persisted queries, ensuring that the hash generated from the document is used. This example demonstrates how to integrate the `persistedExchange` and provide a custom `generateHash` function. ```typescript import { cacheExchange, createClient } from '@urql/core' import { persistedExchange } from '@urql/exchange-persisted' const client = new createClient({ url: 'YOUR_GRAPHQL_ENDPOINT', exchanges: [ cacheExchange, persistedExchange({ enforcePersistedQueries: true, enableForMutation: true, generateHash: (_, document) => Promise.resolve(document['__meta__']['hash']) }) ] }) ``` -------------------------------- ### Usage Examples Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typescript-apollo-next.mdx Examples demonstrating how to use specific configuration options. ```APIDOC ### `importDocumentNodeExternallyFrom` Usage Examples #### Example 1: Importing from a specific file ```ts filename="codegen.ts" import type { CodegenConfig } from '@graphql-codegen/cli' const config: CodegenConfig = { // ... generates: { 'path/to/file': { // plugins... config: { documentMode: 'external', importDocumentNodeExternallyFrom: 'path/to/document-node-file' } } } } export default config ``` #### Example 2: Using 'near-operation-file' mode ```ts filename="codegen.ts" import type { CodegenConfig } from '@graphql-codegen/cli' const config: CodegenConfig = { // ... generates: { 'path/to/file': { // plugins... config: { documentMode: 'external', importDocumentNodeExternallyFrom: 'near-operation-file' } } } } export default config ``` ### `scalars` Usage Example ```ts filename="codegen.ts" import type { CodegenConfig } from '@graphql-codegen/cli' const config: CodegenConfig = { // ... generates: { 'path/to/file': { // plugins... config: { scalars: { DateTime: 'Date', JSON: '{ [key: string]: any }' } } } } } export default config ``` ### `namingConvention` Usage Examples #### Override All Names ```ts filename="codegen.ts" import type { CodegenConfig } from '@graphql-codegen/cli' const config: CodegenConfig = { // ... generates: { 'path/to/file': { // plugins... config: { namingConvention: 'change-case-all#lowerCase' } } } } export default config ``` ``` -------------------------------- ### Setup package.json for Code Generation Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/components/java-installation.mdx Create a package.json file in your project root. The 'postinstall' script ensures graphql-codegen runs after dependencies are installed. ```json { "name": "java-app", "scripts": { "postinstall": "graphql-codegen" }, "dependencies": { "graphql": "14.5.8", "@graphql-codegen/cli": "1.7.0", "@graphql-codegen/RELEVANT_PLUGIN": "1.7.0" } } ``` -------------------------------- ### Multi-File Setup with Import-Types Preset (Old) Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/migration/operations-and-client-preset-from-5-0.mdx Example of a multi-file setup using the 'import-types' preset to reuse base types generated by the 'typescript' plugin. ```typescript const config: CodegenConfig = { // ... generates: { 'src/graphql/base-types.generated.ts': { plugins: ['typescript'] }, 'src/project-1/types.generated.ts': { documents: 'src/project-1/**/*.graphql.ts', preset: 'import-types', plugins: ['typescript-operations'], presetConfig: { typesPath: '../graphql/base-types.generated.ts' } }, 'src/project-2/types.generated.ts': { documents: 'src/project-2/**/*.graphql.ts', preset: 'import-types', plugins: ['typescript-operations'], presetConfig: { typesPath: '../graphql/base-types.generated.ts' } } } } ``` -------------------------------- ### Install SWC Client Preset Plugin Source: https://github.com/dotansimha/graphql-code-generator/blob/master/packages/presets/swc-plugin/README.md Install the plugin as a development dependency. ```bash pnpm add -D @graphql-codegen/client-preset-swc-plugin ``` -------------------------------- ### Install KitQL dependencies Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/guides/svelte.mdx Install the necessary client and development dependencies for KitQL. ```sh npm i @kitql/client npm i -D @kitql/graphql-codegen ``` -------------------------------- ### Install dependencies Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/guides/api-testing.mdx Install the required runtime and development dependencies for the project. ```sh npm i graphql-yoga ``` ```sh npm i -D typescript ts-node @graphql-codegen/cli jest @babel/core @babel/preset-env @babel/preset-typescript babel-jest @graphql-typed-document-node/core ``` -------------------------------- ### Example Configuration with Hooks Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/config-reference/lifecycle-hooks.mdx Example `codegen.ts` configurations demonstrating how to implement root-level and output-level hooks. ```APIDOC ```ts import { CodegenConfig } from '@graphql-codegen/cli' const config: CodegenConfig = { schema: 'http://localhost:4000/graphql', documents: ['src/**/*.tsx'], generates: { './src/gql/': { preset: 'client' } }, hooks: { afterOneFileWrite: ['prettier --write'] } } export default config ``` Or, for specific output: ```ts import { CodegenConfig } from '@graphql-codegen/cli' const config: CodegenConfig = { schema: 'http://localhost:4000/graphql', documents: ['src/**/*.tsx'], generates: { './src/gql/': { preset: 'client', hooks: { afterOneFileWrite: ['prettier --write'] } } } } export default config ``` ``` -------------------------------- ### Install generated dependencies Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/getting-started/installation.mdx Install the packages selected during the initialization wizard process. ```sh npm install ``` -------------------------------- ### Usage Example Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/java/java-apollo-android.mdx A link to a repository demonstrating a working example of using the java-apollo-android plugin with AppSync. ```APIDOC ## Usage Example ### Description This section provides a link to a repository that showcases a practical implementation of the `java-apollo-android` plugin within an Android project using AWS AppSync. ### Example Repository For a working example, please refer to the following repository: [https://github.com/dotansimha/graphql-codegen-appsync-android-example](https://github.com/dotansimha/graphql-codegen-appsync-android-example) ``` -------------------------------- ### Install Dependencies Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/guides/flutter-freezed.mdx Install required GraphQL and code generation packages. ```sh npm i graphql npm i -D typescript @graphql-codegen/cli @graphql-codegen/flutter-freezed ``` -------------------------------- ### Installation and Configuration Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/java/java-apollo-android.mdx Instructions for installing the necessary packages and configuring the codegen.yml file for the java-apollo-android preset. ```APIDOC ## Installation and Configuration ### Description This section covers the initial setup required to use the `java-apollo-android` plugin, including installing dependencies and creating a configuration file. ### Environment Setup Ensure you have Node.js (version 10 or later) and NPM or Yarn installed. ### Installation Navigate to your Android project directory and run the following commands: ```sh npm init --yes npm install graphql npm install -D @graphql-codegen/cli @graphql-codegen/java-apollo-android ``` Or using Yarn: ```sh yarn init -y yarn add graphql yarn add -D @graphql-codegen/cli @graphql-codegen/java-apollo-android ``` ### Configuration (`codegen.yml`) Create a `codegen.yml` file in your project root with the following content, replacing `POINT_TO_YOUR_SCHEMA` and `POINT_TO_YOUR_GRAPHQL_OPERATIONS` with your actual schema and operations file paths: ```yaml schema: POINT_TO_YOUR_SCHEMA documents: POINT_TO_YOUR_GRAPHQL_OPERATIONS generates: ./app/src/main/java/: # Output directory for generated Java code preset: java-apollo-android config: package: 'com.my.app.generated.graphql' # Your desired Java package name fragmentPackage: 'com.my.app.generated.graphql' # Package for fragments typePackage: 'type' # Package for types plugins: - java-apollo-android ``` ### `.gitignore` Configuration Add `node_modules` to your `.gitignore` file to prevent committing unnecessary files. ### Gradle Integration To automatically generate code before each build, add the following to your app's `build.gradle` file: ```gradle preBuild.doFirst { def proc = "yarn graphql-codegen".execute() proc.waitForProcessOutput(System.out, System.err) } build.dependsOn preBuild ``` This ensures that the GraphQL code generation runs as part of your Android build process. ``` -------------------------------- ### Add Descriptions and Examples with @oclif Directive Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typescript-oclif.mdx Use the @oclif directive within your GraphQL mutations or queries to add descriptions and examples for your oclif commands. Multiple 'example' keys are required for multiple examples. ```graphql mutation CreateAuthor($name: String!) @oclif( description: "Create a new author" example: "cli author:create --name Alice" example: "cli author:create --name Bob" ) { createAuthor(input: { name: $name }) { name } } ``` -------------------------------- ### Install Nhost TypeScript SDK Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typescript-nhost.mdx Install the Nhost TypeScript SDK to use with the generated schema. ```bash npm i --save @nhost/nhost-js ``` -------------------------------- ### Install Dependencies with npm Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/java/java-apollo-android.mdx Install the necessary packages for the GraphQL Code Generator and the java-apollo-android plugin. Ensure Node.js is installed. ```sh npm init --yes npm install graphql npm install -D @graphql-codegen/cli @graphql-codegen/java-apollo-android ``` -------------------------------- ### Run initialization wizard Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/getting-started/installation.mdx Execute the interactive CLI wizard to configure the project setup. ```sh npx graphql-code-generator init ``` -------------------------------- ### Install Dependencies Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/README.md Run this command from the root directory to install project dependencies using pnpm. ```sh pnpm install ``` -------------------------------- ### Usage Example Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typescript-vue-urql.mdx Example demonstrating how to use the generated code with a GraphQL query and the `useTestQuery` hook. ```APIDOC ## GraphQL Query ### Description This is an example GraphQL query. ### Query ```graphql query Test { feed { id commentCount repository { full_name html_url owner { avatar_url } } } } ``` ## Generated Code Usage ### Description Example of how to use the generated hook in a Vue.js component. ### Method `useTestQuery` (generated hook) ### Code Example ```ts const { data } = useTestQuery(...) ``` ``` -------------------------------- ### Install core dependencies Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/getting-started/installation.mdx Install the required graphql package and development dependencies for the CLI and TypeScript. ```sh npm i graphql npm i -D typescript @graphql-codegen/cli ``` -------------------------------- ### Implement custom fetcher examples Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typescript-react-query.mdx Example implementations for fetchers with isReactHook set to false or true. ```tsx export const fetchData = ( query: string, variables?: TVariables, options?: RequestInit['headers'] ): (() => Promise) => { return async () => { const res = await fetch('https://api.url', { method: 'POST', headers: { 'Content-Type': 'application/json', ...options }, body: JSON.stringify({ query, variables }) }) const json = await res.json() if (json.errors) { const { message } = json.errors[0] || {} throw new Error(message || 'Error…') } return json.data } } ``` ```tsx export const useFetchData = ( query: string, options?: RequestInit['headers'] ): ((variables?: TVariables) => Promise) => { // it is safe to call React Hooks here. const { url, headers } = React.useContext(FetchParamsContext) return async (variables?: TVariables) => { const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', ...headers, ...options }, body: JSON.stringify({ query, variables }) }) const json = await res.json() if (json.errors) { const { message } = json.errors[0] || {} throw new Error(message || 'Error…') } return json.data } } ``` -------------------------------- ### Install GraphQL Code Generator and essential plugins Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/migration/apollo-tooling.mdx Install the GraphQL Code Generator CLI along with plugins for TypeScript operations and the near-operation-file preset. This setup is recommended for generating TypeScript types from GraphQL operations and placing generated files alongside their source. ```sh npm i -D @graphql-codegen/cli @graphql-codegen/typescript-operations @graphql-codegen/near-operation-file-preset ``` -------------------------------- ### Install Server Preset Dependencies Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/guides/graphql-server-apollo-yoga-with-server-preset.mdx Installs the GraphQL Code Generator CLI and the server preset package as development dependencies. ```sh npm i -D @graphql-codegen/cli @eddeee888/gcg-typescript-resolver-files ``` -------------------------------- ### Example Class Factory Structure Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/guides/flutter-freezed.mdx Example of generated factory constructors for Droid and Starship types. ```dart required final String name, // @6.b.ii @Default([]) List? friends, // @6.b.iii required List appearsIn, // @6.b.iv String? primaryFunction, // @6.b.v }) = Droid; // @6.a.2 const factory SearchResult.starship({ // @6.c required final String id, // @6.c.i required final String name, // @6.c.ii double? length, // @6.c.iii }) = Starship; // @6.a.3 factory SearchResult.fromJson(Map json) => _$SearchResultFromJson(json); } ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/custom-codegen/contributing.mdx Run this command in the root directory to install all project dependencies for the monorepo. ```sh pnpm i ``` -------------------------------- ### Install GraphQL Modules Preset Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/guides/graphql-modules.mdx Install the necessary packages for generating resolver types in a GraphQL Modules project. ```bash npm i -D @graphql-codegen/graphql-modules-preset @graphql-codegen/typescript-resolvers @graphql-codegen/typescript ``` -------------------------------- ### Install Near Operation File Preset Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/advanced/generated-files-colocation.mdx Install the preset as a development dependency using npm or yarn. ```sh npm i -D @graphql-codegen/near-operation-file-preset ``` -------------------------------- ### Install GraphQL Codegen and Nhost Plugin Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typescript-nhost.mdx Install the necessary packages for GraphQL Codegen and the Nhost TypeScript plugin. ```bash npm i --save-dev @graphql-codegen/cli @graphql-codegen/typescript-nhost ``` -------------------------------- ### Install Dependencies Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/guides/angular.mdx Required packages for setting up the GraphQL Code Generator with Angular. ```bash npm i graphql npm i -D typescript npm i -D @graphql-codegen/cli npm i -D @graphql-codegen/typescript npm i -D @graphql-codegen/typescript-operations npm i -D @graphql-codegen/typescript-apollo-angular ``` -------------------------------- ### Install Codegen Dependencies Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/guides/graphql-server-apollo-yoga.mdx Install the necessary CLI and TypeScript resolver plugins via npm. ```bash npm i -D @graphql-codegen/cli @graphql-codegen/typescript-resolvers @graphql-codegen/typescript ``` -------------------------------- ### Install Kotlin Plugin Dependencies Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/java/kotlin.mdx Install the necessary CLI and plugin packages via npm or yarn in your project. ```bash npm init --yes npm install graphql npm install -D @graphql-codegen/cli @graphql-codegen/kotlin ``` ```bash yarn init --yes yarn add graphql yarn add -D @graphql-codegen/cli @graphql-codegen/kotlin ``` -------------------------------- ### Install GraphQL Codegen Dependencies Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/guides/vanilla-typescript.mdx Install the necessary CLI and plugin packages for GraphQL code generation. ```sh npm install --save-dev @graphql-codegen/cli @parcel/watcher npm install --save-dev @graphql-codegen/schema-ast npm install --save-dev @0no-co/graphqlsp ``` -------------------------------- ### Dotenv configuration example Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/config-reference/require-field.mdx Define environment variables in a .env file and access them within the codegen configuration. ```text SCHEMAURL=https://example.com/graphql APIKEY=ABC123 ``` ```ts import { CodegenConfig } from '@graphql-codegen/cli' const config: CodegenConfig = { schema: { [process.env.SCHEMAURL]: { headers: { apikey: process.env.APIKEY } } } // ... } export default config ``` -------------------------------- ### Install GraphQL Code Generator CLI Source: https://github.com/dotansimha/graphql-code-generator/blob/master/README.md Install the core GraphQL package and the CLI tool as development dependencies. ```bash pnpm add graphql pnpm add -D @graphql-codegen/cli ``` -------------------------------- ### Usage Example: Observable Queries Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typescript-svelte-apollo.mdx Demonstrates how to configure and use the plugin to generate observable Apollo queries. ```APIDOC ## Usage Example: Observable Queries ### GraphQL Schema and Query ```graphql fragment TransactionFragment on TransactionDescription { contractAddress from gasUsed gasPrice input isError to value } query Transactions($address: String) { transactions(address: $address) { ...TransactionFragment } } ``` ### Codegen Configuration ```ts filename="codegen.ts" import type { CodegenConfig } from '@graphql-codegen/cli' const config: CodegenConfig = { schema: 'YOUR_SCHEMA_HERE', documents: './src/**/*.graphql', generates: { 'path/to/file.ts': { plugins: ['typescript', 'typescript-operations', 'graphql-codegen-svelte-apollo'], config: { clientPath: 'PATH_TO_APOLLO_CLIENT' } } } } export default config ``` ### Svelte Component Usage ```svelte
    {#each $t?.data?.transactions || [] as transaction}
  • Sent transaction from {transaction.from} to {transaction.to}
  • {/each}
``` ``` -------------------------------- ### Install Latest GraphQL Codegen CLI and Plugins Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/migration/operations-and-client-preset-from-5-0.mdx Install the latest versions of the GraphQL Codegen CLI, typescript-operations, and client-preset using npm or yarn. ```sh npm i -D @graphql-codegen/cli@latest @graphql-codegen/typescript-operations@latest @graphql-codegen/client-preset@latest ``` -------------------------------- ### Generated import statement example Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/getting-started/esm-typescript-usage.mdx Example of how import statements appear when using .ts extensions. ```ts import { FragmentType } from './fragment-masking.ts' import { graphql } from './gql.ts' ``` -------------------------------- ### Multi-File Setup with typescript-operations (New) Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/migration/operations-and-client-preset-from-5-0.mdx Configure 'typescript-operations' for a multi-file setup, using 'generateOperationTypes: false' and 'importSchemaTypesFrom' for shared types. The 'importSchemaTypesFrom' path is relative to the Codegen config location. ```typescript const config: CodegenConfig = { // ... generates: { 'src/graphql/base-types.generated.ts': { documents: 'src/**/*.graphql.ts' // Parses all files with GraphQL documents to generate Enum and Input types that are used by every project plugins: ['typescript-operations'], config: { generateOperationTypes: false, // `generateOperationTypes:false` means only Input, Enum and shared utility types are generated } }, 'src/project-1/types.generated.ts': { documents: 'src/project-1/**/*.graphql.ts', // Only parses GraphQL documents within project-1's scope plugins: ['typescript-operations'], config: { importSchemaTypesFrom: 'src/shared/base-types.generated.ts', // this path is relative to Codegen config location (unlike `typesPath` in the old setup) } }, 'src/project-2/types.generated.ts': { documents: 'src/project-2/**/*.graphql.ts', // Only parses GraphQL documents within project-2's scope plugins: ['typescript-operations'], config: { importSchemaTypesFrom: 'src/shared/base-types.generated.ts', }, } } } ``` -------------------------------- ### Install Svelte Apollo Plugin Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/guides/svelte.mdx Command to install the necessary dependencies for the Svelte Apollo plugin. ```sh npm i -D graphql-codegen-svelte-apollo @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/cli typescript graphql ``` -------------------------------- ### Install GraphQL Code Generator CLI and Dependencies Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/guides/react-vue.mdx Install necessary packages for GraphQL Code Generator, including the CLI and a file watcher, using npm or yarn. ```sh npm install graphql npm install --save-dev typescript @graphql-codegen/cli @parcel/watcher ``` -------------------------------- ### Install graphql-scalars Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/guides/graphql-server-apollo-yoga-with-server-preset.mdx Install the graphql-scalars package using npm or yarn. This is the first step to adding custom scalars. ```sh npm i graphql-scalars ``` -------------------------------- ### Usage Example: Async Queries Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typescript-svelte-apollo.mdx Demonstrates how to configure and use the plugin to generate promise-based (async) Apollo queries. ```APIDOC ## Usage Example: Async Queries ### GraphQL Schema and Query ```graphql fragment TransactionFragment on TransactionDescription { contractAddress from gasUsed gasPrice input isError to value } query Transactions($address: String) { transactions(address: $address) { ...TransactionFragment } } ``` ### Codegen Configuration ```ts filename="codegen.ts" import type { CodegenConfig } from '@graphql-codegen/cli' const config: CodegenConfig = { schema: 'YOUR_SCHEMA_HERE', documents: './src/**/*.graphql', generates: { 'path/to/file.ts': { plugins: ['typescript', 'typescript-operations', 'graphql-codegen-svelte-apollo'], config: { clientPath: 'PATH_TO_APOLLO_CLIENT', asyncQuery: true } } } } export default config ``` ### Svelte Component Usage ```svelte
    {#await AsyncTransactions({ address })} Loading… {:then transactions} {#each transactions || [] as transaction}
  • Sent transaction from {transaction.from} to {transaction.to}
  • {/each} {/await}
``` ``` -------------------------------- ### GraphQL Query Handler Example Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typescript-oclif.mdx Implement a `QueryHandler` function for processing GraphQL requests. This example uses `graphql-request` and logs responses or errors to the command line. Customize the GraphQL client URL as needed. ```typescript import { GraphQLClient } from 'graphql-request' import { Command } from '@oclif/command' interface QueryHandlerProps { command: Command query: string variables?: Record } // Change the URL to the endpoint your CLI will use const client = new GraphQLClient('http://localhost:4000') const handler = ({ command, query, variables }: QueryHandlerProps) => { return client.request(query, variables).then(command.log).catch(command.error) } export default handler ``` -------------------------------- ### Apollo Client Configuration Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/migration/apollo-tooling.mdx Example of an apollo.config.js file used for configuring Apollo Client's codegen. ```javascript module.exports = { client: { service: { name: 'my-service', localSchemaFile: './schema.graphql', }, includes: ['./src/**/*.tsx', './src/**/*.ts'], }, } ``` -------------------------------- ### GraphQL Code Generator Configuration Example Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/custom-codegen/plugin-structure.mdx Example `codegen.yml` configuration for specifying a custom plugin package. This allows the generator to use a published npm package as a plugin. ```yaml schema: my-schema.graphql documents: './src/**/*.graphql' generates: plugins: output.ts: - my-custom-plugin-package ``` -------------------------------- ### Install watch mode support Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/getting-started/installation.mdx Add @parcel/watcher to enable watch mode functionality. ```sh npm i -D @parcel/watcher ``` -------------------------------- ### Custom Schema Loader Implementation Example Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/config-reference/schema-field.mdx An example of a custom schema loader function that returns a GraphQLSchema object. This function can contain custom logic for fetching or building the schema. ```javascript const { readFileSync } = require('node:fs') const { buildSchema } = require('graphql') module.exports = (schemaString, config) => { // Your logic for loading your GraphQLSchema return buildSchema(readFileSync(schemaString, 'utf8')) } ``` -------------------------------- ### Download GraphQL Schema Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/guides/flutter-freezed.mdx Install the schema retrieval tool globally and fetch the schema from a remote endpoint. ```sh npm install -g get-graphql-schema get-graphql-schema https://your-graphql-endpoint > schema.graphql ``` -------------------------------- ### Configure Naming Conventions Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typescript-apollo-next.mdx Examples for controlling naming styles of generated types and enum values. ```ts import type { CodegenConfig } from '@graphql-codegen/cli' const config: CodegenConfig = { // ... generates: { 'path/to/file': { // plugins... config: { namingConvention: { typeNames: 'change-case-all#pascalCase', enumValues: 'change-case-all#upperCase' } } } } } export default config ``` ```ts import type { CodegenConfig } from '@graphql-codegen/cli' const config: CodegenConfig = { // ... generates: { 'path/to/file': { // plugins... config: { namingConvention: 'keep' } } } } export default config ``` ```ts import type { CodegenConfig } from '@graphql-codegen/cli' const config: CodegenConfig = { // ... generates: { 'path/to/file': { // plugins... config: { namingConvention: { typeNames: 'change-case-all#pascalCase', transformUnderscore: true } } } } } export default config ``` -------------------------------- ### Generated Vue/urql Hook Usage Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typescript-vue-urql.mdx Example of how to use the generated hook in a Vue component. Ensure you have the necessary setup for urql and the generated types. ```typescript const { data } = useTestQuery(...) ``` -------------------------------- ### Custom Document Loader Implementation Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/config-reference/documents-field.mdx Provides an example implementation of a custom document loader that reads a file and parses it into a DocumentNode. ```javascript const { readFileSync } = require('node:fs') const { parse } = require('graphql') module.exports = (docString, config) => { return parse(readFileSync(docString, 'utf8')) } ``` -------------------------------- ### Define a GraphQL query with client-side directives Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/integrations/apollo-local-state.mdx Example of a query using the @client directive for local state management. ```graphql query myQuery { todos { id title checked selected @client } } ``` -------------------------------- ### GraphQL Query Example Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typescript-stencil-apollo.mdx This is an example GraphQL query that can be used with the typescript-stencil-apollo plugin. ```graphql query Test { feed { id commentCount repository { full_name html_url owner { avatar_url } } } } ``` -------------------------------- ### Configure client-preset in codegen.ts Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/migration/operations-and-client-preset-from-5-0.mdx Configure the 'client' preset in your codegen.ts file. No changes are required for the default setup when using client-preset. ```typescript const config: CodegenConfig = { // ... generates: { 'src/gql/': { preset: 'client' } } } ``` -------------------------------- ### Initialize GraphQL Code Generator Source: https://github.com/dotansimha/graphql-code-generator/blob/master/README.md Run the init command to interactively set up your GraphQL Code Generator configuration. ```bash pnpm graphql-codegen init ``` -------------------------------- ### GraphQL Schema Modules Example Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/guides/graphql-server-apollo-yoga-with-server-preset.mdx Demonstrates splitting a GraphQL schema into modular files for better organization and maintainability. Each file defines types and extensions for specific domains. ```graphql type Query type Mutation ``` ```graphql extend type Query { user(id: ID!): User } type User { id: ID! fullName: String! isAdmin: Boolean! } ``` ```graphql extend type Query { book(id: ID!): Book } extend type Mutation { markBookAsRead(id: ID!): Book! } type Book { id: ID! isbn: String! } ``` -------------------------------- ### Generate and Run Server Source: https://github.com/dotansimha/graphql-code-generator/blob/master/examples/typescript-resolvers/README.md Use these commands to generate the type-safe GraphQL code and then run the development server. ```bash pnpm codegen ``` ```bash pnpm dev ``` -------------------------------- ### Build the App Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/README.md Run this command from the root directory to build the NextJS application for production. ```sh pnpm build ``` -------------------------------- ### Build and Test Project Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/custom-codegen/contributing.mdx Execute these commands from the root directory to build all common/core packages and ensure all tests are passing. ```sh pnpm build pnpm test ``` -------------------------------- ### Configure project files Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/guides/api-testing.mdx Boilerplate configuration files for TypeScript, Babel, and Jest. ```json { "compilerOptions": { "target": "ES2018", "module": "Node16", "outDir": "dist" }, "include": ["src/**/*"] } ``` ```js module.exports = { presets: [ ['@babel/preset-env', { targets: { node: process.versions.node.split('.')[0] } }], '@babel/preset-typescript' ] } ``` ```js module.exports = { transform: { '^.+\.ts': 'babel-jest' } } ``` -------------------------------- ### Entity and Embedded Directives Example Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typescript-mongodb.mdx An example demonstrating the use of @entity and @embedded directives to generate database models for complex types like User and Profile. ```APIDOC ## Example Usage of @entity and @embedded ### Description This example illustrates how to define GraphQL types with `@entity` and `@embedded` directives to generate corresponding database models, including relationships like `@link` and embedded objects. ### Example GraphQL Schema ```graphql type User @entity { id: String! @id username: String! @column email: String! @column profile: Profile! @embedded friendsCount: Int! # this field won't get a generated MongoDB field friends: [User]! @link } type Profile @entity(embedded: true) { name: String! @column age: Int! @column } ``` ### Generated MongoDB Models (TypeScript) ```ts import { ObjectId } from 'mongodb' export interface UserDbObject { _id: ObjectId username: string email: string profile: ProfileDbObject friends: ObjectId[] } export interface ProfileDbObject { name: string age: string } ``` ``` -------------------------------- ### Importing and Using Plugins Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins.mdx This snippet shows how to import the `useData` hook and `PluginsMarketplaceSearch` component, and then use them to display a list of plugins. It also includes static props generation. ```javascript import { useData } from '@theguild/components' import { PluginsMarketplaceSearch } from '../components/plugins-marketplace-search' export { getPluginsStaticProps as getStaticProps } from '../components/plugins-marketplace-search' export default () => { const plugins = useData() return ( <> ) } ``` -------------------------------- ### Install and configure typescript-compatibility plugin Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/migration/from-0-18.mdx Install the 'typescript-compatibility' plugin using npm and add it to your codegen configuration to generate backward compatibility for 'typescript-operations' and 'typescript-react-apollo' plugins. ```sh npm i -D @graphql-codegen/typescript-compatibility ``` ```yaml ./my-file.ts: schema: schema.json plugins: - typescript - typescript-operations - typescript-compatibility ``` -------------------------------- ### Configure Plugin Dependencies Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/custom-codegen/contributing.mdx Set up the essential dependencies for your plugin, including `@graphql-codegen/plugin-helpers` and `tslib`. Ensure `graphql` is a peer dependency. ```json { "dependencies": { "@graphql-codegen/plugin-helpers": "X.Y.Z", "tslib": "^2.8.0" }, "peerDependencies": { "graphql": "^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0" } } ``` -------------------------------- ### Update typescript-operations for One-File Setup Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/migration/operations-and-client-preset-from-5-0.mdx In the one-file setup, remove the 'typescript' plugin and use only 'typescript-operations'. This plugin now generates only used Input, Enum, and Operation types. ```typescript const config: CodegenConfig = { // ... generates: { 'src/graphql/types.generated.ts': { plugins: ['typescript', 'typescript-operations'], plugins: ['typescript-operations'] } } } ``` -------------------------------- ### Generated TypedDocumentNode Example Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typed-document-node.mdx This example shows the structure of a TypedDocumentNode generated by the 'typed-document-node' plugin, including the operation's variables type, result type, and the DocumentNode itself with generics for types. ```typescript // Represents the variables type of the operation - generated by `typescript` + `typescript-operations` plugins export type RatesQueryVariables = Exact { currency: Scalars['String']; }; // Represents the result type of the operation - generated by `typescript` + `typescript-operations` plugins export type RatesQuery = ( { __typename?: 'Query' } & { rates?: Maybe )>>> } ) // Generated by this plugin - creates a pre-compiled `DocumentNode` and passes result type and variables type as generics export const ratesQuery: TypedDocumentNode = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'query', name: { ... } } ] } ``` -------------------------------- ### Basic Codegen Configuration Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/config-reference/codegen-config.mdx Define schema, documents, and generation targets in a `codegen.ts` file. This example configures the 'client' preset for generating types from schema and documents. ```typescript import { CodegenConfig } from '@graphql-codegen/cli' const config: CodegenConfig = { schema: 'http://localhost:4000/graphql', documents: ['src/**/*.tsx'], generates: { './src/gql/': { preset: 'client' } } } export default config ``` -------------------------------- ### Add multiple content blocks with placement Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/other/add.mdx Demonstrates using an array of content and specifying placement options like append to wrap generated code. ```ts import type { CodegenConfig } from '@graphql-codegen/cli' const config: CodegenConfig = { // ... generates: { 'path/to/file.ts': { plugins: [ { add: { content: ['declare namespace GraphQL {'] } }, { add: { placement: 'append', content: '}' } }, 'typescript' ] } } } export default config ``` -------------------------------- ### Integrate with GraphQL Yoga Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/guides/graphql-server-apollo-yoga-with-server-preset.mdx Set up a GraphQL server using GraphQL Yoga by providing the generated type definitions and resolvers. ```ts import { createServer } from 'http' import { createSchema, createYoga } from 'graphql-yoga' import { resolvers } from './schema/resolvers.generated' import { typeDefs } from './schema/typeDefs.generated' const yoga = createYoga({ schema: createSchema({ typeDefs, resolvers }) }) const server = createServer(yoga) server.listen(3000) ``` -------------------------------- ### Implement Yoga Test Suite Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/guides/api-testing.mdx A complete test file setup using a helper function to execute GraphQL operations against a Yoga server instance. ```typescript import { print, type ExecutionResult } from 'graphql' import type { TypedDocumentNode } from '@graphql-typed-document-node/core' import { graphql } from './gql' import { yoga } from './yoga' function executeOperation( operation: TypedDocumentNode, ...[variables]: TVariables extends Record ? [] : [TVariables] ): Promise> { return Promise.resolve( yoga.fetch('http://yoga/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify({ query: print(operation), variables: variables ?? undefined }) }) ).then(response => response.json()) } describe('Yoga Tests', () => { it('execute query operation', async () => { const HelloQuery = graphql(/* GraphQL */ ` query HelloQuery { hello } `) const result = await executeOperation(HelloQuery) expect(result.data?.hello).toEqual('Hello world!') }) it('execute mutation operation', async () => { const EchoMutation = graphql(/* GraphQL */ ` mutation EchoMutation($message: String!) { echo(message: $message) } `) const result = await executeOperation(EchoMutation, { message: 'Ohayoo!' }) expect(result.data?.echo).toEqual('Ohayoo!') }) it('execute mutation operation (variant)', async () => { const EchoMutation = graphql(/* GraphQL */ ` mutation EchoMutation($message: String!) { echo(message: $message) } `) const result = await executeOperation(EchoMutation, { message: 'Konbanwa' }) expect(result.data?.echo).toEqual('Konbanwa') }) }) ``` -------------------------------- ### Define a GraphQL query Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typescript-document-nodes.mdx Example GraphQL operation used as input for the generator. ```graphql query Viewer { viewer { login name } } ``` -------------------------------- ### GraphQL Yoga with Typed Resolvers Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/getting-started/index.mdx Demonstrates setting up a GraphQL server using GraphQL Yoga with type-safe resolvers. It uses generated `Resolvers` types and creates a schema from type definitions. ```typescript import { readFileSync } from 'node:fs' import { createServer } from 'node:http' import { createYoga, createSchema } from 'graphql-yoga' import { Resolvers } from './resolvers-types' const typeDefs = readFileSync('./schema.graphql', 'utf8') const resolvers: Resolvers = { Query: { // typed resolvers! } } const schema = createSchema({ typeDefs, resolvers }) const yoga = createYoga({ schema }) const server = createServer(yoga) server.listen(4000, () => { console.log('GraphQL Server is listening on http://localhost:4000/graphql'); }) ``` -------------------------------- ### GraphQL Code Generator Configuration with Plugin Options Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/custom-codegen/plugin-structure.mdx Example `codegen.yml` demonstrating how to pass custom configuration options to a plugin. The `my-plugin.js` accepts `myConfig` as a parameter. ```yaml schema: my-schema.graphql documents: './src/**/*.graphql' generates: output.ts: plugins: - my-plugin.js: myConfig: 'some-value' ``` -------------------------------- ### typescript-react-apollo Configuration Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typescript-react-apollo.mdx Configuration guide for integrating the typescript-react-apollo plugin into your codegen.ts file. ```APIDOC ## Configuration: typescript-react-apollo ### Description Configures the GraphQL Code Generator to output React Hooks based on provided GraphQL operations. ### Request Body (codegen.ts configuration) - **plugins** (array) - Required - List containing 'typescript', 'typescript-operations', and 'typescript-react-apollo'. - **config.withComponent** (boolean) - Optional - Enables generation of data components (deprecated in Apollo Client v3). - **config.withHOC** (boolean) - Optional - Enables generation of High-Order-Components (deprecated in Apollo Client v3). ### Request Example ```ts import type { CodegenConfig } from '@graphql-codegen/cli' const config: CodegenConfig = { schema: 'YOUR_SCHEMA_HERE', documents: './src/**/*.graphql', generates: { './generated-types.ts': { plugins: ['typescript', 'typescript-operations', 'typescript-react-apollo'], config: { withComponent: true, withHOC: true } } } } export default config ``` ``` -------------------------------- ### Use generated React hook Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typescript-urql.mdx Example of using the generated hook for querying data. ```ts const [result] = useTestQuery(...) ``` -------------------------------- ### Generated Component Usage Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typescript-stencil-apollo.mdx Example of how to use a component generated by the typescript-stencil-apollo plugin with variables. ```tsx ``` -------------------------------- ### Define TypedDocumentNode structure Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/guides/react-vue.mdx Example of how the client preset generates GraphQL documents with TypedDocumentNode. ```ts const query: TypedDocumentNode<{ greetings: string }, never | Record> = parse( /* GraphQL */ ` query greetings { greetings } ` ) ``` -------------------------------- ### Typed GraphQL Query Implementations Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/getting-started/index.mdx Examples of using generated types with frontend frameworks. ```tsx import { useQuery } from 'urql' import { graphql } from './gql/gql' // postsQueryDocument is now fully typed! const postsQueryDocument = graphql(/* GraphQL */ ` query Posts { posts { id title author { id firstName lastName } } } `) const Posts = () => { // URQL's `useQuery()` knows how to work with typed graphql documents const [result] = useQuery({ query: postsQueryDocument }) // `result` is fully typed! // … } ``` ```tsx import { request } from 'graphql-request' import { useQuery } from '@tanstack/react-query' import { graphql } from './gql/gql' // postsQueryDocument is now fully typed! const postsQueryDocument = graphql(/* GraphQL */ ` ``` -------------------------------- ### Define a GraphQL query Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typescript-apollo-angular.mdx Create a .graphql file to define the operations you want to generate services for. ```graphql query MyFeed { feed { id commentCount } } ``` -------------------------------- ### Define GraphQL Schema Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/docs/guides/angular.mdx Example GraphQL schema definition used for generating types. ```graphql type Author { id: Int! firstName: String! lastName: String! posts(findTitle: String): [Post] } type Post { id: Int! title: String! author: Author } type Query { posts: [Post] } ``` -------------------------------- ### Invoke GraphQL Query with C# Client Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/c-sharp/c-sharp-operations.mdx Demonstrates initializing a GraphQLHttpClient and executing a query using the generated request. ```csharp using GraphQL.Client.Http; using GraphQL.Client.Serializer.Newtonsoft; ... using var client = new GraphQLHttpClient("https://gqlserver", new NewtonsoftJsonSerializer()); var response = await client.SendQueryAsync(UsersGQL.Request()); ``` -------------------------------- ### Configure External Document Mode Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typescript-apollo-next.mdx Examples showing how to set documentMode to external using either a specific file path or the near-operation-file preset. ```typescript import type { CodegenConfig } from '@graphql-codegen/cli' const config: CodegenConfig = { // ... generates: { 'path/to/file': { // plugins... config: { documentMode: 'external', importDocumentNodeExternallyFrom: 'path/to/document-node-file' } } } } export default config ``` ```typescript import type { CodegenConfig } from '@graphql-codegen/cli' const config: CodegenConfig = { // ... generates: { 'path/to/file': { // plugins... config: { documentMode: 'external', importDocumentNodeExternallyFrom: 'near-operation-file' } } } } export default config ``` -------------------------------- ### Persisted Documents JSON Example Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/presets/preset-client.mdx This file maps document hashes to their GraphQL query strings. ```json { "b2c3d4e5f6g7h8i9j0a1": "query Hello { hello }", "kae4fe7f6g7h8i9ej0ag": "mutation echo($msg: String!) { echo(message: $msg) }" } ``` -------------------------------- ### Implement Request Timing Middleware Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typescript-graphql-request.mdx Example of a middleware function that logs the duration of GraphQL requests. ```ts const client = new GraphQLClient('') const clientTimingWrapper: SdkFunctionWrapper = async (action: () => Promise): Promise => { const startTime = new Date() const result = await action() console.log('request duration (ms)', new Date() - startTime) return result } const sdk = getSdk(client, clientTimingWrapper) ``` -------------------------------- ### Mock GraphQL Query Responses Source: https://github.com/dotansimha/graphql-code-generator/blob/master/website/src/pages/plugins/typescript/typescript-msw.mdx Examples for mocking successful and error responses for a GraphQL query. ```ts import { mockGetUserQuery } from './generated' import { HttpResponse } from 'msw' const mockSuccess = mockGetUserQuery(({ variables }) => { const { id } = variables return HttpResponse.json({ data: { getUser: { name: 'John Doe', id } } }) }) export mockUserQuerySuccess; ``` ```ts import { mockGetUserQuery } from './generated' import { HttpResponse } from 'msw' const mockUserQueryError = mockGetUserQuery(({ variables }) => { return HttpResponse.json({ errors: [ { message: 'User not found' } ] }) }) export mockUserQueryError; ```