Graphql Code Generator Versions Save

A tool for generating code based on a GraphQL schema and GraphQL operations (query/mutation/subscription), with flexible support for custom plugins.

release-1680576611161

1 year ago

@graphql-codegen/[email protected]

Minor Changes

  • #9151 b7dacb21f Thanks @eddeee888! - Add watchPattern config option for generates sections.

    By default, watch mode automatically watches all GraphQL schema and document files. This means when a change is detected, Codegen CLI is run.

    A user may want to run Codegen CLI when non-schema and non-document files are changed. Each generates section now has a watchPattern option to allow more file patterns to be added to the list of patterns to watch.

    In the example below, mappers are exported from schema.mappers.ts files. We want to re-run Codegen if the content of *.mappers.ts files change because they change the generated types file. To solve this, we can add mapper file patterns to watch using the glob pattern used for schema and document files.

    // codegen.ts
    const config: CodegenConfig = {
      schema: 'src/schema/**/*.graphql',
      generates: {
        'src/schema/types.ts': {
          plugins: ['typescript', 'typescript-resolvers'],
          config: {
            mappers: {
              User: './user/schema.mappers#UserMapper',
              Book: './book/schema.mappers#BookMapper',
            },
          }
          watchPattern: 'src/schema/**/*.mappers.ts', // Watches mapper files in `watch` mode. Use an array for multiple patterns e.g. `['src/*.pattern1.ts','src/*.pattern2.ts']`
        },
      },
    };
    

    Then, run Codegen CLI in watch mode:

    yarn graphql-codegen --watch
    

    Now, updating *.mappers.ts files re-runs Codegen! 🎉

    Note: watchPattern is only used in watch mode i.e. running CLI with --watch flag.

Patch Changes

@graphql-codegen/[email protected]

Minor Changes

  • #9146 9f4d9c5a4 Thanks @eddeee888! - [typescript-resolvers] Add resolversNonOptionalTypename config option.

    This is extending on ResolversUnionTypes implemented in https://github.com/dotansimha/graphql-code-generator/pull/9069

    resolversNonOptionalTypename adds non-optional __typename to union members of ResolversUnionTypes, without affecting the union members' base intefaces.

    A common use case for non-optional __typename of union members is using it as the common field to work out the final schema type. This makes implementing the union's __resolveType very simple as we can use __typename to decide which union member the resolved object is. Without this, we have to check the existence of field/s on the incoming object which could be verbose.

    For example, consider this schema:

    type Query {
      book(id: ID!): BookPayload!
    }
    
    type Book {
      id: ID!
      isbn: String!
    }
    
    type BookResult {
      node: Book
    }
    
    type PayloadError {
      message: String!
    }
    
    union BookPayload = BookResult | PayloadError
    

    With optional __typename: We need to check existence of certain fields to resolve type in the union resolver:

    // Query/book.ts
    export const book = async () => {
      try {
        const book = await fetchBook();
        // 1. No `__typename` in resolver results...
        return {
          node: book,
        };
      } catch (e) {
        return {
          message: 'Failed to fetch book',
        };
      }
    };
    
    // BookPayload.ts
    export const BookPayload = {
      __resolveType: parent => {
        // 2. ... means more checks in `__resolveType`
        if ('message' in parent) {
          return 'PayloadError';
        }
        return 'BookResult';
      },
    };
    

    With non-optional __typename: Resolvers declare the type. This which gives us better TypeScript support in resolvers and simplify __resolveType implementation:

    // Query/book.ts
    export const book = async () => {
      try {
        const book = await fetchBook();
        // 1. `__typename` is declared in resolver results...
        return {
          __typename: 'BookResult', // 1a. this also types `node` for us 🎉
          node: book,
        };
      } catch (e) {
        return {
          __typename: 'PayloadError',
          message: 'Failed to fetch book',
        };
      }
    };
    
    // BookPayload.ts
    export const BookPayload = {
      __resolveType: parent => parent.__typename, // 2. ... means a very simple check in `__resolveType`
    };
    

    Using resolversNonOptionalTypename: add it into typescript-resolvers plugin config:

    // codegen.ts
    const config: CodegenConfig = {
      schema: 'src/schema/**/*.graphql',
      generates: {
        'src/schema/types.ts': {
          plugins: ['typescript', 'typescript-resolvers'],
          config: {
            resolversNonOptionalTypename: true, // Or `resolversNonOptionalTypename: { unionMember: true }`
          },
        },
      },
    };
    

Patch Changes

  • #9206 e56790104 Thanks @eddeee888! - Fix ResolversUnionTypes being used in ResolversParentTypes

    Previously, objects with mappable fields are converted to Omit format that references its own type group or ResolversTypes or ResolversParentTypes e.g.

    export type ResolversTypes = {
      Book: ResolverTypeWrapper<BookMapper>;
      BookPayload: ResolversTypes['BookResult'] | ResolversTypes['StandardError'];
      // Note: `result` on the next line references `ResolversTypes["Book"]`
      BookResult: ResolverTypeWrapper<Omit<BookResult, 'result'> & { result?: Maybe<ResolversTypes['Book']> }>;
      StandardError: ResolverTypeWrapper<StandardError>;
    };
    
    export type ResolversParentTypes = {
      Book: BookMapper;
      BookPayload: ResolversParentTypes['BookResult'] | ResolversParentTypes['StandardError'];
      // Note: `result` on the next line references `ResolversParentTypes["Book"]`
      BookResult: Omit<BookResult, 'result'> & { result?: Maybe<ResolversParentTypes['Book']> };
      StandardError: StandardError;
    };
    

    In https://github.com/dotansimha/graphql-code-generator/pull/9069, we extracted resolver union types to its own group:

    export type ResolversUnionTypes = {
      // Note: `result` on the next line references `ResolversTypes["Book"]` which is only correct for the `ResolversTypes` case
      BookPayload: (Omit<BookResult, 'result'> & { result?: Maybe<ResolversTypes['Book']> }) | StandardError;
    };
    
    export type ResolversTypes = {
      Book: ResolverTypeWrapper<BookMapper>;
      BookPayload: ResolverTypeWrapper<ResolversUnionTypes['BookPayload']>;
      BookResult: ResolverTypeWrapper<Omit<BookResult, 'result'> & { result?: Maybe<ResolversTypes['Book']> }>;
      StandardError: ResolverTypeWrapper<StandardError>;
    };
    
    export type ResolversParentTypes = {
      Book: BookMapper;
      BookPayload: ResolversUnionTypes['BookPayload'];
      BookResult: Omit<BookResult, 'result'> & { result?: Maybe<ResolversParentTypes['Book']> };
      StandardError: StandardError;
    };
    

    This change creates an extra ResolversUnionParentTypes that is referenced by ResolversParentTypes to ensure backwards compatibility:

    export type ResolversUnionTypes = {
      BookPayload: (Omit<BookResult, 'result'> & { result?: Maybe<ResolversParentTypes['Book']> }) | StandardError;
    };
    
    // ... and the reference is changed in ResolversParentTypes:
    export type ResolversParentTypes = {
      // ... other fields
      BookPayload: ResolversUnionParentTypes['BookPayload'];
    };
    
  • #9194 acb647e4e Thanks @dstaley! - Don't emit import statements for unused fragments

  • Updated dependencies [b7dacb21f, f104619ac]:

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Major Changes

  • #9137 2256c8b5d Thanks @beerose! - Add TypedDocumentNode string alternative that doesn't require GraphQL AST on the client. This change requires @graphql-typed-document-node/core in version 3.2.0 or higher.

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Minor Changes

  • #9146 9f4d9c5a4 Thanks @eddeee888! - [typescript-resolvers] Add resolversNonOptionalTypename config option.

    This is extending on ResolversUnionTypes implemented in https://github.com/dotansimha/graphql-code-generator/pull/9069

    resolversNonOptionalTypename adds non-optional __typename to union members of ResolversUnionTypes, without affecting the union members' base intefaces.

    A common use case for non-optional __typename of union members is using it as the common field to work out the final schema type. This makes implementing the union's __resolveType very simple as we can use __typename to decide which union member the resolved object is. Without this, we have to check the existence of field/s on the incoming object which could be verbose.

    For example, consider this schema:

    type Query {
      book(id: ID!): BookPayload!
    }
    
    type Book {
      id: ID!
      isbn: String!
    }
    
    type BookResult {
      node: Book
    }
    
    type PayloadError {
      message: String!
    }
    
    union BookPayload = BookResult | PayloadError
    

    With optional __typename: We need to check existence of certain fields to resolve type in the union resolver:

    // Query/book.ts
    export const book = async () => {
      try {
        const book = await fetchBook();
        // 1. No `__typename` in resolver results...
        return {
          node: book,
        };
      } catch (e) {
        return {
          message: 'Failed to fetch book',
        };
      }
    };
    
    // BookPayload.ts
    export const BookPayload = {
      __resolveType: parent => {
        // 2. ... means more checks in `__resolveType`
        if ('message' in parent) {
          return 'PayloadError';
        }
        return 'BookResult';
      },
    };
    

    With non-optional __typename: Resolvers declare the type. This which gives us better TypeScript support in resolvers and simplify __resolveType implementation:

    // Query/book.ts
    export const book = async () => {
      try {
        const book = await fetchBook();
        // 1. `__typename` is declared in resolver results...
        return {
          __typename: 'BookResult', // 1a. this also types `node` for us 🎉
          node: book,
        };
      } catch (e) {
        return {
          __typename: 'PayloadError',
          message: 'Failed to fetch book',
        };
      }
    };
    
    // BookPayload.ts
    export const BookPayload = {
      __resolveType: parent => parent.__typename, // 2. ... means a very simple check in `__resolveType`
    };
    

    Using resolversNonOptionalTypename: add it into typescript-resolvers plugin config:

    // codegen.ts
    const config: CodegenConfig = {
      schema: 'src/schema/**/*.graphql',
      generates: {
        'src/schema/types.ts': {
          plugins: ['typescript', 'typescript-resolvers'],
          config: {
            resolversNonOptionalTypename: true, // Or `resolversNonOptionalTypename: { unionMember: true }`
          },
        },
      },
    };
    

Patch Changes

  • #9206 e56790104 Thanks @eddeee888! - Fix ResolversUnionTypes being used in ResolversParentTypes

    Previously, objects with mappable fields are converted to Omit format that references its own type group or ResolversTypes or ResolversParentTypes e.g.

    export type ResolversTypes = {
      Book: ResolverTypeWrapper<BookMapper>;
      BookPayload: ResolversTypes['BookResult'] | ResolversTypes['StandardError'];
      // Note: `result` on the next line references `ResolversTypes["Book"]`
      BookResult: ResolverTypeWrapper<Omit<BookResult, 'result'> & { result?: Maybe<ResolversTypes['Book']> }>;
      StandardError: ResolverTypeWrapper<StandardError>;
    };
    
    export type ResolversParentTypes = {
      Book: BookMapper;
      BookPayload: ResolversParentTypes['BookResult'] | ResolversParentTypes['StandardError'];
      // Note: `result` on the next line references `ResolversParentTypes["Book"]`
      BookResult: Omit<BookResult, 'result'> & { result?: Maybe<ResolversParentTypes['Book']> };
      StandardError: StandardError;
    };
    

    In https://github.com/dotansimha/graphql-code-generator/pull/9069, we extracted resolver union types to its own group:

    export type ResolversUnionTypes = {
      // Note: `result` on the next line references `ResolversTypes["Book"]` which is only correct for the `ResolversTypes` case
      BookPayload: (Omit<BookResult, 'result'> & { result?: Maybe<ResolversTypes['Book']> }) | StandardError;
    };
    
    export type ResolversTypes = {
      Book: ResolverTypeWrapper<BookMapper>;
      BookPayload: ResolverTypeWrapper<ResolversUnionTypes['BookPayload']>;
      BookResult: ResolverTypeWrapper<Omit<BookResult, 'result'> & { result?: Maybe<ResolversTypes['Book']> }>;
      StandardError: ResolverTypeWrapper<StandardError>;
    };
    
    export type ResolversParentTypes = {
      Book: BookMapper;
      BookPayload: ResolversUnionTypes['BookPayload'];
      BookResult: Omit<BookResult, 'result'> & { result?: Maybe<ResolversParentTypes['Book']> };
      StandardError: StandardError;
    };
    

    This change creates an extra ResolversUnionParentTypes that is referenced by ResolversParentTypes to ensure backwards compatibility:

    export type ResolversUnionTypes = {
      BookPayload: (Omit<BookResult, 'result'> & { result?: Maybe<ResolversParentTypes['Book']> }) | StandardError;
    };
    
    // ... and the reference is changed in ResolversParentTypes:
    export type ResolversParentTypes = {
      // ... other fields
      BookPayload: ResolversUnionParentTypes['BookPayload'];
    };
    
  • f104619ac Thanks @saihaj! - Resolve issue with nesting fields in @provides directive being prevented

  • Updated dependencies [e56790104, b7dacb21f, f104619ac, 92d86b009, acb647e4e, 9f4d9c5a4]:

@graphql-codegen/[email protected]

Major Changes

  • #9137 2256c8b5d Thanks @beerose! - Add TypedDocumentNode string alternative that doesn't require GraphQL AST on the client. This change requires @graphql-typed-document-node/core in version 3.2.0 or higher.

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Major Changes

  • #9137 2256c8b5d Thanks @beerose! - Add TypedDocumentNode string alternative that doesn't require GraphQL AST on the client. This change requires @graphql-typed-document-node/core in version 3.2.0 or higher.

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Minor Changes

  • #9151 b7dacb21f Thanks @eddeee888! - Add watchPattern config option for generates sections.

    By default, watch mode automatically watches all GraphQL schema and document files. This means when a change is detected, Codegen CLI is run.

    A user may want to run Codegen CLI when non-schema and non-document files are changed. Each generates section now has a watchPattern option to allow more file patterns to be added to the list of patterns to watch.

    In the example below, mappers are exported from schema.mappers.ts files. We want to re-run Codegen if the content of *.mappers.ts files change because they change the generated types file. To solve this, we can add mapper file patterns to watch using the glob pattern used for schema and document files.

    // codegen.ts
    const config: CodegenConfig = {
      schema: 'src/schema/**/*.graphql',
      generates: {
        'src/schema/types.ts': {
          plugins: ['typescript', 'typescript-resolvers'],
          config: {
            mappers: {
              User: './user/schema.mappers#UserMapper',
              Book: './book/schema.mappers#BookMapper',
            },
          }
          watchPattern: 'src/schema/**/*.mappers.ts', // Watches mapper files in `watch` mode. Use an array for multiple patterns e.g. `['src/*.pattern1.ts','src/*.pattern2.ts']`
        },
      },
    };
    

    Then, run Codegen CLI in watch mode:

    yarn graphql-codegen --watch
    

    Now, updating *.mappers.ts files re-runs Codegen! 🎉

    Note: watchPattern is only used in watch mode i.e. running CLI with --watch flag.

Patch Changes

  • f104619ac Thanks @saihaj! - Resolve issue with nesting fields in @provides directive being prevented

release-1678189242418

1 year ago

@graphql-cli/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

release-1677178671969

1 year ago

@graphql-cli/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

release-1677093821450

1 year ago

@graphql-cli/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Minor Changes

Patch Changes

release-1676995873

1 year ago

@graphql-codegen/[email protected]

Minor Changes

  • #8893 a118c307a Thanks @n1ru4l! - It is no longer mandatory to declare an empty plugins array when using a preset

  • #8723 a3309e63e Thanks @kazekyo! - Introduce a new feature called DocumentTransform.

    DocumentTransform is a functionality that allows you to modify documents before they are processed by plugins. You can use functions passed to the documentTransforms option to make changes to GraphQL documents.

    To use this feature, you can write documentTransforms as follows:

    import type { CodegenConfig } from '@graphql-codegen/cli';
    
    const config: CodegenConfig = {
      schema: 'https://localhost:4000/graphql',
      documents: ['src/**/*.tsx'],
      generates: {
        './src/gql/': {
          preset: 'client',
          documentTransforms: [
            {
              transform: ({ documents }) => {
                // Make some changes to the documents
                return documents;
              },
            },
          ],
        },
      },
    };
    export default config;
    

    For instance, to remove a @localOnlyDirective directive from documents, you can write the following code:

    import type { CodegenConfig } from '@graphql-codegen/cli';
    import { visit } from 'graphql';
    
    const config: CodegenConfig = {
      schema: 'https://localhost:4000/graphql',
      documents: ['src/**/*.tsx'],
      generates: {
        './src/gql/': {
          preset: 'client',
          documentTransforms: [
            {
              transform: ({ documents }) => {
                return documents.map(documentFile => {
                  documentFile.document = visit(documentFile.document, {
                    Directive: {
                      leave(node) {
                        if (node.name.value === 'localOnlyDirective') return null;
                      },
                    },
                  });
                  return documentFile;
                });
              },
            },
          ],
        },
      },
    };
    export default config;
    

    DocumentTransform can also be specified by file name. You can create a custom file for a specific transformation and pass it to documentTransforms.

    Let's create the document transform as a file:

    module.exports = {
      transform: ({ documents }) => {
        // Make some changes to the documents
        return documents;
      },
    };
    

    Then, you can specify the file name as follows:

    import type { CodegenConfig } from '@graphql-codegen/cli';
    
    const config: CodegenConfig = {
      schema: 'https://localhost:4000/graphql',
      documents: ['src/**/*.tsx'],
      generates: {
        './src/gql/': {
          preset: 'client',
          documentTransforms: ['./my-document-transform.js'],
        },
      },
    };
    export default config;
    

Patch Changes

@graphql-codegen/[email protected]

Minor Changes

  • #8723 a3309e63e Thanks @kazekyo! - Introduce a new feature called DocumentTransform.

    DocumentTransform is a functionality that allows you to modify documents before they are processed by plugins. You can use functions passed to the documentTransforms option to make changes to GraphQL documents.

    To use this feature, you can write documentTransforms as follows:

    import type { CodegenConfig } from '@graphql-codegen/cli';
    
    const config: CodegenConfig = {
      schema: 'https://localhost:4000/graphql',
      documents: ['src/**/*.tsx'],
      generates: {
        './src/gql/': {
          preset: 'client',
          documentTransforms: [
            {
              transform: ({ documents }) => {
                // Make some changes to the documents
                return documents;
              },
            },
          ],
        },
      },
    };
    export default config;
    

    For instance, to remove a @localOnlyDirective directive from documents, you can write the following code:

    import type { CodegenConfig } from '@graphql-codegen/cli';
    import { visit } from 'graphql';
    
    const config: CodegenConfig = {
      schema: 'https://localhost:4000/graphql',
      documents: ['src/**/*.tsx'],
      generates: {
        './src/gql/': {
          preset: 'client',
          documentTransforms: [
            {
              transform: ({ documents }) => {
                return documents.map(documentFile => {
                  documentFile.document = visit(documentFile.document, {
                    Directive: {
                      leave(node) {
                        if (node.name.value === 'localOnlyDirective') return null;
                      },
                    },
                  });
                  return documentFile;
                });
              },
            },
          ],
        },
      },
    };
    export default config;
    

    DocumentTransform can also be specified by file name. You can create a custom file for a specific transformation and pass it to documentTransforms.

    Let's create the document transform as a file:

    module.exports = {
      transform: ({ documents }) => {
        // Make some changes to the documents
        return documents;
      },
    };
    

    Then, you can specify the file name as follows:

    import type { CodegenConfig } from '@graphql-codegen/cli';
    
    const config: CodegenConfig = {
      schema: 'https://localhost:4000/graphql',
      documents: ['src/**/*.tsx'],
      generates: {
        './src/gql/': {
          preset: 'client',
          documentTransforms: ['./my-document-transform.js'],
        },
      },
    };
    export default config;
    

Patch Changes

@graphql-codegen/[email protected]

Minor Changes

Patch Changes

@graphql-codegen/[email protected]

Minor Changes

  • #8893 a118c307a Thanks @n1ru4l! - It is no longer mandatory to declare an empty plugins array when using a preset

  • #8723 a3309e63e Thanks @kazekyo! - Introduce a new feature called DocumentTransform.

    DocumentTransform is a functionality that allows you to modify documents before they are processed by plugins. You can use functions passed to the documentTransforms option to make changes to GraphQL documents.

    To use this feature, you can write documentTransforms as follows:

    import type { CodegenConfig } from '@graphql-codegen/cli';
    
    const config: CodegenConfig = {
      schema: 'https://localhost:4000/graphql',
      documents: ['src/**/*.tsx'],
      generates: {
        './src/gql/': {
          preset: 'client',
          documentTransforms: [
            {
              transform: ({ documents }) => {
                // Make some changes to the documents
                return documents;
              },
            },
          ],
        },
      },
    };
    export default config;
    

    For instance, to remove a @localOnlyDirective directive from documents, you can write the following code:

    import type { CodegenConfig } from '@graphql-codegen/cli';
    import { visit } from 'graphql';
    
    const config: CodegenConfig = {
      schema: 'https://localhost:4000/graphql',
      documents: ['src/**/*.tsx'],
      generates: {
        './src/gql/': {
          preset: 'client',
          documentTransforms: [
            {
              transform: ({ documents }) => {
                return documents.map(documentFile => {
                  documentFile.document = visit(documentFile.document, {
                    Directive: {
                      leave(node) {
                        if (node.name.value === 'localOnlyDirective') return null;
                      },
                    },
                  });
                  return documentFile;
                });
              },
            },
          ],
        },
      },
    };
    export default config;
    

    DocumentTransform can also be specified by file name. You can create a custom file for a specific transformation and pass it to documentTransforms.

    Let's create the document transform as a file:

    module.exports = {
      transform: ({ documents }) => {
        // Make some changes to the documents
        return documents;
      },
    };
    

    Then, you can specify the file name as follows:

    import type { CodegenConfig } from '@graphql-codegen/cli';
    
    const config: CodegenConfig = {
      schema: 'https://localhost:4000/graphql',
      documents: ['src/**/*.tsx'],
      generates: {
        './src/gql/': {
          preset: 'client',
          documentTransforms: ['./my-document-transform.js'],
        },
      },
    };
    export default config;
    

Patch Changes

@graphql-codegen/[email protected]

Minor Changes

  • #8893 a118c307a Thanks @n1ru4l! - It is no longer mandatory to declare an empty plugins array when using a preset

  • #8723 a3309e63e Thanks @kazekyo! - Introduce a new feature called DocumentTransform.

    DocumentTransform is a functionality that allows you to modify documents before they are processed by plugins. You can use functions passed to the documentTransforms option to make changes to GraphQL documents.

    To use this feature, you can write documentTransforms as follows:

    import type { CodegenConfig } from '@graphql-codegen/cli';
    
    const config: CodegenConfig = {
      schema: 'https://localhost:4000/graphql',
      documents: ['src/**/*.tsx'],
      generates: {
        './src/gql/': {
          preset: 'client',
          documentTransforms: [
            {
              transform: ({ documents }) => {
                // Make some changes to the documents
                return documents;
              },
            },
          ],
        },
      },
    };
    export default config;
    

    For instance, to remove a @localOnlyDirective directive from documents, you can write the following code:

    import type { CodegenConfig } from '@graphql-codegen/cli';
    import { visit } from 'graphql';
    
    const config: CodegenConfig = {
      schema: 'https://localhost:4000/graphql',
      documents: ['src/**/*.tsx'],
      generates: {
        './src/gql/': {
          preset: 'client',
          documentTransforms: [
            {
              transform: ({ documents }) => {
                return documents.map(documentFile => {
                  documentFile.document = visit(documentFile.document, {
                    Directive: {
                      leave(node) {
                        if (node.name.value === 'localOnlyDirective') return null;
                      },
                    },
                  });
                  return documentFile;
                });
              },
            },
          ],
        },
      },
    };
    export default config;
    

    DocumentTransform can also be specified by file name. You can create a custom file for a specific transformation and pass it to documentTransforms.

    Let's create the document transform as a file:

    module.exports = {
      transform: ({ documents }) => {
        // Make some changes to the documents
        return documents;
      },
    };
    

    Then, you can specify the file name as follows:

    import type { CodegenConfig } from '@graphql-codegen/cli';
    
    const config: CodegenConfig = {
      schema: 'https://localhost:4000/graphql',
      documents: ['src/**/*.tsx'],
      generates: {
        './src/gql/': {
          preset: 'client',
          documentTransforms: ['./my-document-transform.js'],
        },
      },
    };
    export default config;
    

Patch Changes

@graphql-codegen/[email protected]

Minor Changes

  • #8723 a3309e63e Thanks @kazekyo! - Introduce a new feature called DocumentTransform.

    DocumentTransform is a functionality that allows you to modify documents before they are processed by plugins. You can use functions passed to the documentTransforms option to make changes to GraphQL documents.

    To use this feature, you can write documentTransforms as follows:

    import type { CodegenConfig } from '@graphql-codegen/cli';
    
    const config: CodegenConfig = {
      schema: 'https://localhost:4000/graphql',
      documents: ['src/**/*.tsx'],
      generates: {
        './src/gql/': {
          preset: 'client',
          documentTransforms: [
            {
              transform: ({ documents }) => {
                // Make some changes to the documents
                return documents;
              },
            },
          ],
        },
      },
    };
    export default config;
    

    For instance, to remove a @localOnlyDirective directive from documents, you can write the following code:

    import type { CodegenConfig } from '@graphql-codegen/cli';
    import { visit } from 'graphql';
    
    const config: CodegenConfig = {
      schema: 'https://localhost:4000/graphql',
      documents: ['src/**/*.tsx'],
      generates: {
        './src/gql/': {
          preset: 'client',
          documentTransforms: [
            {
              transform: ({ documents }) => {
                return documents.map(documentFile => {
                  documentFile.document = visit(documentFile.document, {
                    Directive: {
                      leave(node) {
                        if (node.name.value === 'localOnlyDirective') return null;
                      },
                    },
                  });
                  return documentFile;
                });
              },
            },
          ],
        },
      },
    };
    export default config;
    

    DocumentTransform can also be specified by file name. You can create a custom file for a specific transformation and pass it to documentTransforms.

    Let's create the document transform as a file:

    module.exports = {
      transform: ({ documents }) => {
        // Make some changes to the documents
        return documents;
      },
    };
    

    Then, you can specify the file name as follows:

    import type { CodegenConfig } from '@graphql-codegen/cli';
    
    const config: CodegenConfig = {
      schema: 'https://localhost:4000/graphql',
      documents: ['src/**/*.tsx'],
      generates: {
        './src/gql/': {
          preset: 'client',
          documentTransforms: ['./my-document-transform.js'],
        },
      },
    };
    export default config;
    

Patch Changes

@graphql-codegen/[email protected]

Minor Changes

  • #8893 a118c307a Thanks @n1ru4l! - mark plugins in config optional

  • #8723 a3309e63e Thanks @kazekyo! - Introduce a new feature called DocumentTransform.

    DocumentTransform is a functionality that allows you to modify documents before they are processed by plugins. You can use functions passed to the documentTransforms option to make changes to GraphQL documents.

    To use this feature, you can write documentTransforms as follows:

    import type { CodegenConfig } from '@graphql-codegen/cli';
    
    const config: CodegenConfig = {
      schema: 'https://localhost:4000/graphql',
      documents: ['src/**/*.tsx'],
      generates: {
        './src/gql/': {
          preset: 'client',
          documentTransforms: [
            {
              transform: ({ documents }) => {
                // Make some changes to the documents
                return documents;
              },
            },
          ],
        },
      },
    };
    export default config;
    

    For instance, to remove a @localOnlyDirective directive from documents, you can write the following code:

    import type { CodegenConfig } from '@graphql-codegen/cli';
    import { visit } from 'graphql';
    
    const config: CodegenConfig = {
      schema: 'https://localhost:4000/graphql',
      documents: ['src/**/*.tsx'],
      generates: {
        './src/gql/': {
          preset: 'client',
          documentTransforms: [
            {
              transform: ({ documents }) => {
                return documents.map(documentFile => {
                  documentFile.document = visit(documentFile.document, {
                    Directive: {
                      leave(node) {
                        if (node.name.value === 'localOnlyDirective') return null;
                      },
                    },
                  });
                  return documentFile;
                });
              },
            },
          ],
        },
      },
    };
    export default config;
    

    DocumentTransform can also be specified by file name. You can create a custom file for a specific transformation and pass it to documentTransforms.

    Let's create the document transform as a file:

    module.exports = {
      transform: ({ documents }) => {
        // Make some changes to the documents
        return documents;
      },
    };
    

    Then, you can specify the file name as follows:

    import type { CodegenConfig } from '@graphql-codegen/cli';
    
    const config: CodegenConfig = {
      schema: 'https://localhost:4000/graphql',
      documents: ['src/**/*.tsx'],
      generates: {
        './src/gql/': {
          preset: 'client',
          documentTransforms: ['./my-document-transform.js'],
        },
      },
    };
    export default config;
    

Patch Changes

@graphql-cli/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

release-1675419690826

1 year ago

@graphql-cli/[email protected]

Major Changes

Patch Changes

@graphql-codegen/[email protected]

Major Changes

Patch Changes

@graphql-codegen/[email protected]

Major Changes

Patch Changes

@graphql-codegen/[email protected]

Major Changes

Patch Changes

@graphql-codegen/[email protected]

Major Changes

Patch Changes

@graphql-codegen/[email protected]

Major Changes

Patch Changes

@graphql-codegen/[email protected]

Major Changes

Patch Changes

@graphql-codegen/[email protected]

Major Changes

Patch Changes

@graphql-codegen/[email protected]

Major Changes

Patch Changes

@graphql-codegen/[email protected]

Major Changes

Patch Changes

@graphql-codegen/[email protected]

Major Changes

Patch Changes

@graphql-codegen/[email protected]

Major Changes

Patch Changes

@graphql-codegen/[email protected]

Major Changes

Patch Changes

@graphql-codegen/[email protected]

Major Changes

Patch Changes

@graphql-codegen/[email protected]

Major Changes

Patch Changes

@graphql-codegen/[email protected]

Major Changes

Patch Changes

@graphql-codegen/[email protected]

Major Changes

Patch Changes

@graphql-codegen/[email protected]

Major Changes

Patch Changes

@graphql-codegen/[email protected]

Major Changes

Patch Changes

@graphql-codegen/[email protected]

Major Changes

Patch Changes

release-1675118180331

1 year ago

@graphql-codegen/[email protected]

Patch Changes

release-1675088794682

1 year ago

@graphql-cli/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

  • #8816 a98198524 Thanks @charle692! - Fix issue where visitor-plugin-common emitted ESM imports for Operations when emitLegacyCommonJSImports is true

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Minor Changes

  • #8757 4f290aa72 Thanks @n1ru4l! - Add support for persisted documents.

    You can now generate and embed a persisted documents hash for the executable documents.

    /** codegen.ts */
    import { CodegenConfig } from '@graphql-codegen/cli';
    
    const config: CodegenConfig = {
      schema: 'https://swapi-graphql.netlify.app/.netlify/functions/index',
      documents: ['src/**/*.tsx'],
      ignoreNoDocuments: true, // for better experience with the watcher
      generates: {
        './src/gql/': {
          preset: 'client',
          plugins: [],
          presetConfig: {
            persistedDocuments: true,
          },
        },
      },
    };
    
    export default config;
    

    This will generate ./src/gql/persisted-documents.json (dictionary of hashes with their operation string).

    In addition to that each generated document node will have a __meta__.hash property.

    import { gql } from './gql.js';
    
    const allFilmsWithVariablesQueryDocument = graphql(/* GraphQL */ `
      query allFilmsWithVariablesQuery($first: Int!) {
        allFilms(first: $first) {
          edges {
            node {
              ...FilmItem
            }
          }
        }
      }
    `);
    
    console.log((allFilmsWithVariablesQueryDocument as any)['__meta__']['hash']);
    
  • #8757 4f290aa72 Thanks @n1ru4l! - Add support for embedding metadata in the document AST.

    It is now possible to embed metadata (e.g. for your GraphQL client within the emitted code).

    /** codegen.ts */
    import { CodegenConfig } from '@graphql-codegen/cli';
    
    const config: CodegenConfig = {
      schema: 'https://swapi-graphql.netlify.app/.netlify/functions/index',
      documents: ['src/**/*.tsx'],
      ignoreNoDocuments: true, // for better experience with the watcher
      generates: {
        './src/gql/': {
          preset: 'client',
          plugins: [],
          presetConfig: {
            onExecutableDocumentNode(documentNode) {
              return {
                operation: documentNode.definitions[0].operation,
                name: documentNode.definitions[0].name.value,
              };
            },
          },
        },
      },
    };
    
    export default config;
    

    You can then access the metadata via the __meta__ property on the document node.

    import { gql } from './gql.js';
    
    const allFilmsWithVariablesQueryDocument = graphql(/* GraphQL */ `
      query allFilmsWithVariablesQuery($first: Int!) {
        allFilms(first: $first) {
          edges {
            node {
              ...FilmItem
            }
          }
        }
      }
    `);
    
    console.log((allFilmsWithVariablesQueryDocument as any)['__meta__']);
    

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

release-1673379174923

1 year ago

@graphql-cli/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

  • #8796 902451601 Thanks @shmax! - remove extra asterisk and add missing semicolon in generated output

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

release-1672850402615

1 year ago

@graphql-cli/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Minor Changes

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes