graphql-code-generator

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

MIT License

Downloads
157.7M
Stars
10.6K
Committers
543

Bot releases are visible (Hide)

graphql-code-generator - March 27, 2024 Latest Release

Published by theguild-bot 7 months ago

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

graphql-code-generator - February 22, 2024

Published by theguild-bot 8 months ago

@graphql-codegen/[email protected]

Minor Changes

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

graphql-code-generator - February 20, 2024

Published by theguild-bot 8 months ago

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Major 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-code-generator - February 06, 2024

Published by theguild-bot 9 months ago

@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

@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-code-generator - February 06, 2024

Published by theguild-bot 9 months ago

@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-code-generator - July 25, 2023

Published by theguild-bot about 1 year ago

@graphql-codegen/[email protected]

Major Changes

Patch Changes

@graphql-codegen/[email protected]

Minor Changes

  • #9562 5beee9794 Thanks @n1ru4l! - Add the addTypenameSelectionDocumentTransform for automatically adding __typename selections to all objct type selection sets.

    This is useful for GraphQL Clients such as Apollo Client or urql that need typename information for their cache to function.

    Example Usage

    import { addTypenameSelectionDocumentTransform } from '@graphql-codegen/client-preset';
    import { CodegenConfig } from "@graphql-codegen/cli";
    
    const config: CodegenConfig = {
      schema: "YOUR_GRAPHQL_ENDPOINT",
      documents: ["./**/*.{ts,tsx}"],
      ignoreNoDocuments: true,
      generates: {
        "./gql/": {
          preset: "client",
          plugins: [],
          presetConfig: {
            persistedDocuments: true,
          },
          documentTransforms: [addTypenameSelectionDocumentTransform],
        },
      },
    };
    
    export default config;
    

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

graphql-code-generator - June 19, 2023

Published by theguild-bot over 1 year ago

@graphql-codegen/[email protected]

Patch Changes

  • #9497 2276708d0 Thanks @eddeee888! - Revert default ID scalar input type to string

    We changed the ID Scalar input type from string to string | number in the latest major version of typescript plugin. This causes issues for server plugins (e.g. typescript-resolvers) that depends on typescript plugin. This is because the scalar type needs to be manually inverted on setup which is confusing.

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

  • #9497 2276708d0 Thanks @eddeee888! - Revert default ID scalar input type to string

    We changed the ID Scalar input type from string to string | number in the latest major version of typescript plugin. This causes issues for server plugins (e.g. typescript-resolvers) that depends on typescript plugin. This is because the scalar type needs to be manually inverted on setup which is confusing.

  • Updated dependencies [2276708d0]:

@graphql-codegen/[email protected]

Patch Changes

  • #9497 2276708d0 Thanks @eddeee888! - Revert default ID scalar input type to string

    We changed the ID Scalar input type from string to string | number in the latest major version of typescript plugin. This causes issues for server plugins (e.g. typescript-resolvers) that depends on typescript plugin. This is because the scalar type needs to be manually inverted on setup which is confusing.

  • Updated dependencies [2276708d0]:

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

  • #9497 2276708d0 Thanks @eddeee888! - Revert default ID scalar input type to string

    We changed the ID Scalar input type from string to string | number in the latest major version of typescript plugin. This causes issues for server plugins (e.g. typescript-resolvers) that depends on typescript plugin. This is because the scalar type needs to be manually inverted on setup which is confusing.

  • Updated dependencies [2276708d0]:

@graphql-codegen/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

graphql-code-generator - June 01, 2023

Published by theguild-bot over 1 year ago

@graphql-codegen/[email protected]

Patch Changes

graphql-code-generator - May 24, 2023

Published by theguild-bot over 1 year ago

@graphql-codegen/[email protected]

Major Changes

  • bb66c2a31 Thanks @n1ru4l! - Require Node.js >= 16. Drop support for Node.js 14

Patch Changes

@graphql-codegen/[email protected]

Major Changes

  • bb66c2a31 Thanks @n1ru4l! - Require Node.js >= 16. Drop support for Node.js 14

Patch Changes

@graphql-codegen/[email protected]

Major Changes

  • bb66c2a31 Thanks @n1ru4l! - Require Node.js >= 16. Drop support for Node.js 14

Patch Changes

@graphql-codegen/[email protected]

Major Changes

  • bb66c2a31 Thanks @n1ru4l! - Require Node.js >= 16. Drop support for Node.js 14

Patch Changes

@graphql-codegen/[email protected]

Major Changes

  • bb66c2a31 Thanks @n1ru4l! - Require Node.js >= 16. Drop support for Node.js 14

Patch Changes

@graphql-codegen/[email protected]

Major Changes

  • bb66c2a31 Thanks @n1ru4l! - Require Node.js >= 16. Drop support for Node.js 14

Patch Changes

@graphql-codegen/[email protected]

Major Changes

  • bb66c2a31 Thanks @n1ru4l! - Require Node.js >= 16. Drop support for Node.js 14

Patch Changes

@graphql-codegen/[email protected]

Major Changes

  • #9375 ba84a3a27 Thanks @eddeee888! - Implement Scalars with input/output types

    In GraphQL, Scalar types can be different for client and server. For example, given the native GraphQL ID:

    • A client may send string or number in the input
    • A client receives string in its selection set (i.e output)
    • A server receives string in the resolver (GraphQL parses string or number received from the client to string)
    • A server may return string or number (GraphQL serializes the value to string before sending it to the client )

    Currently, we represent every Scalar with only one type. This is what codegen generates as base type:

    export type Scalars = {
      ID: string;
    };
    

    Then, this is used in both input and output type e.g.

    export type Book = {
      __typename?: 'Book';
      id: Scalars['ID']; // Output's ID can be `string` 👍
    };
    
    export type QueryBookArgs = {
      id: Scalars['ID']; // Input's ID can be `string` or `number`. However, the type is only `string` here 👎
    };
    

    This PR extends each Scalar to have input and output:

    export type Scalars = {
      ID: {
        input: string | number;
        output: string;
      };
    };
    

    Then, each input/output GraphQL type can correctly refer to the correct input/output scalar type:

    export type Book = {
      __typename?: 'Book';
      id: Scalars['ID']['output']; // Output's ID can be `string` 👍
    };
    
    export type QueryBookArgs = {
      id: Scalars['ID']['input']; // Input's ID can be `string` or `number` 👍
    };
    

    Note that for typescript-resolvers, the type of ID needs to be inverted. However, the referenced types in GraphQL input/output types should still work correctly:

    export type Scalars = {
      ID: {
        input: string;
        output: string | number;
      }
    }
    
    export type Book = {
      __typename?: "Book";
      id: Scalars["ID"]['output']; // Resolvers can return `string` or `number` in ID fields 👍
    };
    
    export type QueryBookArgs = {
      id: Scalars["ID"]['input']; // Resolvers receive `string` in ID fields 👍
    };
    
    export type ResolversTypes = {
      ID: ID: ResolverTypeWrapper<Scalars['ID']['output']>; // Resolvers can return `string` or `number` in ID fields 👍
    }
    
    export type ResolversParentTypes = {
      ID: Scalars['ID']['output']; // Resolvers receive `string` or `number` from parents 👍
    };
    

    Config changes:

    1. Scalars option can now take input/output types:
    config: {
      scalars: {
        ID: {
          input: 'string',
          output: 'string | number'
        }
      }
    }
    
    1. If a string is given (instead of an object with input/output fields), it will be used as both input and output types:
    config: {
      scalars: {
        ID: 'string'; // This means `string` will be used for both ID's input and output types
      }
    }
    
    1. BREAKING CHANGE: External module Scalar types need to be an object with input/output fields
    config: {
      scalars: {
        ID: './path/to/scalar-module';
      }
    }
    

    If correctly, wired up, the following will be generated:

    // Previously, imported `ID` type can be a primitive type, now it must be an object with input/output fields
    import { ID } from './path/to/scalar-module';
    
    export type Scalars = {
      ID: { input: ID['input']; output: ID['output'] };
    };
    

    BREAKING CHANGE: This changes Scalar types which could be referenced in other plugins. If you are a plugin maintainer and reference Scalar, please update your plugin to use the correct input/output types.

  • bb66c2a31 Thanks @n1ru4l! - Require Node.js >= 16. Drop support for Node.js 14

Minor Changes

  • #9196 3848a2b73 Thanks @beerose! - Add @defer directive support

    When a query includes a deferred fragment field, the server will return a partial response with the non-deferred fields first, followed by the remaining fields once they have been resolved.

    Once start using the @defer directive in your queries, the generated code will automatically include support for the directive.

    // src/index.tsx
    import { graphql } from './gql';
    const OrdersFragment = graphql(`
      fragment OrdersFragment on User {
        orders {
          id
          total
        }
      }
    `);
    const GetUserQuery = graphql(`
      query GetUser($id: ID!) {
        user(id: $id) {
          id
          name
          ...OrdersFragment @defer
        }
      }
    `);
    

    The generated type for GetUserQuery will have information that the fragment is incremental, meaning it may not be available right away.

    // gql/graphql.ts
    export type GetUserQuery = { __typename?: 'Query'; id: string; name: string } & ({
      __typename?: 'Query';
    } & {
      ' $fragmentRefs'?: { OrdersFragment: Incremental<OrdersFragment> };
    });
    

    Apart from generating code that includes support for the @defer directive, the Codegen also exports a utility function called isFragmentReady. You can use it to conditionally render components based on whether the data for a deferred
    fragment is available:

    const OrdersList = (props: { data: FragmentType<typeof OrdersFragment> }) => {
      const data = useFragment(OrdersFragment, props.data);
      return (
        // render orders list
      )
    };
    
    function App() {
      const { data } = useQuery(GetUserQuery);
      return (
        {data && (
          <>
            {isFragmentReady(GetUserQuery, OrdersFragment, data)
    					&& <OrdersList data={data} />}
          </>
        )}
      );
    }
    export default App;
    
  • #9339 50471e651 Thanks @AaronMoat! - Add excludeTypes config to resolversNonOptionalTypename

    This disables the adding of __typename in resolver types for any specified typename. This could be useful e.g. if you're wanting to enable this for all new types going forward but not do a big migration.

    Usage example:

    const config: CodegenConfig = {
      schema: 'src/schema/**/*.graphql',
      generates: {
        'src/schema/types.ts': {
          plugins: ['typescript', 'typescript-resolvers'],
          config: {
            resolversNonOptionalTypename: {
              unionMember: true,
              excludeTypes: ['MyType'],
            },
          },
        },
      },
    };
    
  • #9229 5aa95aa96 Thanks @eddeee888! - Use generic to simplify ResolversUnionTypes

    This follows the ResolversInterfaceTypes's approach where the RefType generic is used to refer back to ResolversTypes or ResolversParentTypes in cases of nested Union types

  • #9304 e1dc75f3c Thanks @esfomeado! - Added support for disabling suffixes on Enums.

  • #9229 5aa95aa96 Thanks @eddeee888! - Extract interfaces to ResolversInterfaceTypes and add to resolversNonOptionalTypename

    1. ResolversInterfaceTypes is a new type that keeps track of a GraphQL interface and its implementing types.

    For example, consider this schema:

    extend type Query {
      character(id: ID!): CharacterNode
    }
    
    interface CharacterNode {
      id: ID!
    }
    
    type Wizard implements CharacterNode {
      id: ID!
      screenName: String!
      spells: [String!]!
    }
    
    type Fighter implements CharacterNode {
      id: ID!
      screenName: String!
      powerLevel: Int!
    }
    

    The generated types will look like this:

    export type ResolversInterfaceTypes<RefType extends Record<string, unknown>> = {
      CharacterNode: Fighter | Wizard;
    };
    
    export type ResolversTypes = {
      // other types...
      CharacterNode: ResolverTypeWrapper<ResolversInterfaceTypes<ResolversTypes>['CharacterNode']>;
      Fighter: ResolverTypeWrapper<Fighter>;
      Wizard: ResolverTypeWrapper<Wizard>;
      // other types...
    };
    
    export type ResolversParentTypes = {
      // other types...
      CharacterNode: ResolversInterfaceTypes<ResolversParentTypes>['CharacterNode'];
      Fighter: Fighter;
      Wizard: Wizard;
      // other types...
    };
    

    The RefType generic is used to reference back to ResolversTypes and ResolversParentTypes in some cases such as field returning a Union.

    1. resolversNonOptionalTypename also affects ResolversInterfaceTypes

    Using the schema above, if we use resolversNonOptionalTypename option:

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

    Then, the generated type looks like this:

    export type ResolversInterfaceTypes<RefType extends Record<string, unknown>> = {
      CharacterNode: (Fighter & { __typename: 'Fighter' }) | (Wizard & { __typename: 'Wizard' });
    };
    
    export type ResolversTypes = {
      // other types...
      CharacterNode: ResolverTypeWrapper<ResolversInterfaceTypes<ResolversTypes>['CharacterNode']>;
      Fighter: ResolverTypeWrapper<Fighter>;
      Wizard: ResolverTypeWrapper<Wizard>;
      // other types...
    };
    
    export type ResolversParentTypes = {
      // other types...
      CharacterNode: ResolversInterfaceTypes<ResolversParentTypes>['CharacterNode'];
      Fighter: Fighter;
      Wizard: Wizard;
      // other types...
    };
    

Patch Changes

@graphql-codegen/[email protected]

Major Changes

  • bb66c2a31 Thanks @n1ru4l! - Require Node.js >= 16. Drop support for Node.js 14

Patch Changes

@graphql-codegen/[email protected]

Major Changes

  • bb66c2a31 Thanks @n1ru4l! - Require Node.js >= 16. Drop support for Node.js 14

Patch Changes

@graphql-codegen/[email protected]

Major Changes

  • #9375 ba84a3a27 Thanks @eddeee888! - Implement Scalars with input/output types

    In GraphQL, Scalar types can be different for client and server. For example, given the native GraphQL ID:

    • A client may send string or number in the input
    • A client receives string in its selection set (i.e output)
    • A server receives string in the resolver (GraphQL parses string or number received from the client to string)
    • A server may return string or number (GraphQL serializes the value to string before sending it to the client )

    Currently, we represent every Scalar with only one type. This is what codegen generates as base type:

    export type Scalars = {
      ID: string;
    };
    

    Then, this is used in both input and output type e.g.

    export type Book = {
      __typename?: 'Book';
      id: Scalars['ID']; // Output's ID can be `string` 👍
    };
    
    export type QueryBookArgs = {
      id: Scalars['ID']; // Input's ID can be `string` or `number`. However, the type is only `string` here 👎
    };
    

    This PR extends each Scalar to have input and output:

    export type Scalars = {
      ID: {
        input: string | number;
        output: string;
      };
    };
    

    Then, each input/output GraphQL type can correctly refer to the correct input/output scalar type:

    export type Book = {
      __typename?: 'Book';
      id: Scalars['ID']['output']; // Output's ID can be `string` 👍
    };
    
    export type QueryBookArgs = {
      id: Scalars['ID']['input']; // Input's ID can be `string` or `number` 👍
    };
    

    Note that for typescript-resolvers, the type of ID needs to be inverted. However, the referenced types in GraphQL input/output types should still work correctly:

    export type Scalars = {
      ID: {
        input: string;
        output: string | number;
      }
    }
    
    export type Book = {
      __typename?: "Book";
      id: Scalars["ID"]['output']; // Resolvers can return `string` or `number` in ID fields 👍
    };
    
    export type QueryBookArgs = {
      id: Scalars["ID"]['input']; // Resolvers receive `string` in ID fields 👍
    };
    
    export type ResolversTypes = {
      ID: ID: ResolverTypeWrapper<Scalars['ID']['output']>; // Resolvers can return `string` or `number` in ID fields 👍
    }
    
    export type ResolversParentTypes = {
      ID: Scalars['ID']['output']; // Resolvers receive `string` or `number` from parents 👍
    };
    

    Config changes:

    1. Scalars option can now take input/output types:
    config: {
      scalars: {
        ID: {
          input: 'string',
          output: 'string | number'
        }
      }
    }
    
    1. If a string is given (instead of an object with input/output fields), it will be used as both input and output types:
    config: {
      scalars: {
        ID: 'string'; // This means `string` will be used for both ID's input and output types
      }
    }
    
    1. BREAKING CHANGE: External module Scalar types need to be an object with input/output fields
    config: {
      scalars: {
        ID: './path/to/scalar-module';
      }
    }
    

    If correctly, wired up, the following will be generated:

    // Previously, imported `ID` type can be a primitive type, now it must be an object with input/output fields
    import { ID } from './path/to/scalar-module';
    
    export type Scalars = {
      ID: { input: ID['input']; output: ID['output'] };
    };
    

    BREAKING CHANGE: This changes Scalar types which could be referenced in other plugins. If you are a plugin maintainer and reference Scalar, please update your plugin to use the correct input/output types.

  • bb66c2a31 Thanks @n1ru4l! - Require Node.js >= 16. Drop support for Node.js 14

Minor Changes

  • #9196 3848a2b73 Thanks @beerose! - Add @defer directive support

    When a query includes a deferred fragment field, the server will return a partial response with the non-deferred fields first, followed by the remaining fields once they have been resolved.

    Once start using the @defer directive in your queries, the generated code will automatically include support for the directive.

    // src/index.tsx
    import { graphql } from './gql';
    const OrdersFragment = graphql(`
      fragment OrdersFragment on User {
        orders {
          id
          total
        }
      }
    `);
    const GetUserQuery = graphql(`
      query GetUser($id: ID!) {
        user(id: $id) {
          id
          name
          ...OrdersFragment @defer
        }
      }
    `);
    

    The generated type for GetUserQuery will have information that the fragment is incremental, meaning it may not be available right away.

    // gql/graphql.ts
    export type GetUserQuery = { __typename?: 'Query'; id: string; name: string } & ({
      __typename?: 'Query';
    } & {
      ' $fragmentRefs'?: { OrdersFragment: Incremental<OrdersFragment> };
    });
    

    Apart from generating code that includes support for the @defer directive, the Codegen also exports a utility function called isFragmentReady. You can use it to conditionally render components based on whether the data for a deferred
    fragment is available:

    const OrdersList = (props: { data: FragmentType<typeof OrdersFragment> }) => {
      const data = useFragment(OrdersFragment, props.data);
      return (
        // render orders list
      )
    };
    
    function App() {
      const { data } = useQuery(GetUserQuery);
      return (
        {data && (
          <>
            {isFragmentReady(GetUserQuery, OrdersFragment, data)
    					&& <OrdersList data={data} />}
          </>
        )}
      );
    }
    export default App;
    
  • #9304 e1dc75f3c Thanks @esfomeado! - Added support for disabling suffixes on Enums.

Patch Changes

@graphql-codegen/[email protected]

Major Changes

  • #9375 ba84a3a27 Thanks @eddeee888! - Implement Scalars with input/output types

    In GraphQL, Scalar types can be different for client and server. For example, given the native GraphQL ID:

    • A client may send string or number in the input
    • A client receives string in its selection set (i.e output)
    • A server receives string in the resolver (GraphQL parses string or number received from the client to string)
    • A server may return string or number (GraphQL serializes the value to string before sending it to the client )

    Currently, we represent every Scalar with only one type. This is what codegen generates as base type:

    export type Scalars = {
      ID: string;
    };
    

    Then, this is used in both input and output type e.g.

    export type Book = {
      __typename?: 'Book';
      id: Scalars['ID']; // Output's ID can be `string` 👍
    };
    
    export type QueryBookArgs = {
      id: Scalars['ID']; // Input's ID can be `string` or `number`. However, the type is only `string` here 👎
    };
    

    This PR extends each Scalar to have input and output:

    export type Scalars = {
      ID: {
        input: string | number;
        output: string;
      };
    };
    

    Then, each input/output GraphQL type can correctly refer to the correct input/output scalar type:

    export type Book = {
      __typename?: 'Book';
      id: Scalars['ID']['output']; // Output's ID can be `string` 👍
    };
    
    export type QueryBookArgs = {
      id: Scalars['ID']['input']; // Input's ID can be `string` or `number` 👍
    };
    

    Note that for typescript-resolvers, the type of ID needs to be inverted. However, the referenced types in GraphQL input/output types should still work correctly:

    export type Scalars = {
      ID: {
        input: string;
        output: string | number;
      }
    }
    
    export type Book = {
      __typename?: "Book";
      id: Scalars["ID"]['output']; // Resolvers can return `string` or `number` in ID fields 👍
    };
    
    export type QueryBookArgs = {
      id: Scalars["ID"]['input']; // Resolvers receive `string` in ID fields 👍
    };
    
    export type ResolversTypes = {
      ID: ID: ResolverTypeWrapper<Scalars['ID']['output']>; // Resolvers can return `string` or `number` in ID fields 👍
    }
    
    export type ResolversParentTypes = {
      ID: Scalars['ID']['output']; // Resolvers receive `string` or `number` from parents 👍
    };
    

    Config changes:

    1. Scalars option can now take input/output types:
    config: {
      scalars: {
        ID: {
          input: 'string',
          output: 'string | number'
        }
      }
    }
    
    1. If a string is given (instead of an object with input/output fields), it will be used as both input and output types:
    config: {
      scalars: {
        ID: 'string'; // This means `string` will be used for both ID's input and output types
      }
    }
    
    1. BREAKING CHANGE: External module Scalar types need to be an object with input/output fields
    config: {
      scalars: {
        ID: './path/to/scalar-module';
      }
    }
    

    If correctly, wired up, the following will be generated:

    // Previously, imported `ID` type can be a primitive type, now it must be an object with input/output fields
    import { ID } from './path/to/scalar-module';
    
    export type Scalars = {
      ID: { input: ID['input']; output: ID['output'] };
    };
    

    BREAKING CHANGE: This changes Scalar types which could be referenced in other plugins. If you are a plugin maintainer and reference Scalar, please update your plugin to use the correct input/output types.

  • bb66c2a31 Thanks @n1ru4l! - Require Node.js >= 16. Drop support for Node.js 14

Minor Changes

  • #9196 3848a2b73 Thanks @beerose! - Add @defer directive support

    When a query includes a deferred fragment field, the server will return a partial response with the non-deferred fields first, followed by the remaining fields once they have been resolved.

    Once start using the @defer directive in your queries, the generated code will automatically include support for the directive.

    // src/index.tsx
    import { graphql } from './gql';
    const OrdersFragment = graphql(`
      fragment OrdersFragment on User {
        orders {
          id
          total
        }
      }
    `);
    const GetUserQuery = graphql(`
      query GetUser($id: ID!) {
        user(id: $id) {
          id
          name
          ...OrdersFragment @defer
        }
      }
    `);
    

    The generated type for GetUserQuery will have information that the fragment is incremental, meaning it may not be available right away.

    // gql/graphql.ts
    export type GetUserQuery = { __typename?: 'Query'; id: string; name: string } & ({
      __typename?: 'Query';
    } & {
      ' $fragmentRefs'?: { OrdersFragment: Incremental<OrdersFragment> };
    });
    

    Apart from generating code that includes support for the @defer directive, the Codegen also exports a utility function called isFragmentReady. You can use it to conditionally render components based on whether the data for a deferred
    fragment is available:

    const OrdersList = (props: { data: FragmentType<typeof OrdersFragment> }) => {
      const data = useFragment(OrdersFragment, props.data);
      return (
        // render orders list
      )
    };
    
    function App() {
      const { data } = useQuery(GetUserQuery);
      return (
        {data && (
          <>
            {isFragmentReady(GetUserQuery, OrdersFragment, data)
    					&& <OrdersList data={data} />}
          </>
        )}
      );
    }
    export default App;
    
  • #9339 50471e651 Thanks @AaronMoat! - Add excludeTypes config to resolversNonOptionalTypename

    This disables the adding of __typename in resolver types for any specified typename. This could be useful e.g. if you're wanting to enable this for all new types going forward but not do a big migration.

    Usage example:

    const config: CodegenConfig = {
      schema: 'src/schema/**/*.graphql',
      generates: {
        'src/schema/types.ts': {
          plugins: ['typescript', 'typescript-resolvers'],
          config: {
            resolversNonOptionalTypename: {
              unionMember: true,
              excludeTypes: ['MyType'],
            },
          },
        },
      },
    };
    
  • #9229 5aa95aa96 Thanks @eddeee888! - Use generic to simplify ResolversUnionTypes

    This follows the ResolversInterfaceTypes's approach where the RefType generic is used to refer back to ResolversTypes or ResolversParentTypes in cases of nested Union types

  • #9304 e1dc75f3c Thanks @esfomeado! - Added support for disabling suffixes on Enums.

  • #9229 5aa95aa96 Thanks @eddeee888! - Extract interfaces to ResolversInterfaceTypes and add to resolversNonOptionalTypename

    1. ResolversInterfaceTypes is a new type that keeps track of a GraphQL interface and its implementing types.

    For example, consider this schema:

    extend type Query {
      character(id: ID!): CharacterNode
    }
    
    interface CharacterNode {
      id: ID!
    }
    
    type Wizard implements CharacterNode {
      id: ID!
      screenName: String!
      spells: [String!]!
    }
    
    type Fighter implements CharacterNode {
      id: ID!
      screenName: String!
      powerLevel: Int!
    }
    

    The generated types will look like this:

    export type ResolversInterfaceTypes<RefType extends Record<string, unknown>> = {
      CharacterNode: Fighter | Wizard;
    };
    
    export type ResolversTypes = {
      // other types...
      CharacterNode: ResolverTypeWrapper<ResolversInterfaceTypes<ResolversTypes>['CharacterNode']>;
      Fighter: ResolverTypeWrapper<Fighter>;
      Wizard: ResolverTypeWrapper<Wizard>;
      // other types...
    };
    
    export type ResolversParentTypes = {
      // other types...
      CharacterNode: ResolversInterfaceTypes<ResolversParentTypes>['CharacterNode'];
      Fighter: Fighter;
      Wizard: Wizard;
      // other types...
    };
    

    The RefType generic is used to reference back to ResolversTypes and ResolversParentTypes in some cases such as field returning a Union.

    1. resolversNonOptionalTypename also affects ResolversInterfaceTypes

    Using the schema above, if we use resolversNonOptionalTypename option:

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

    Then, the generated type looks like this:

    export type ResolversInterfaceTypes<RefType extends Record<string, unknown>> = {
      CharacterNode: (Fighter & { __typename: 'Fighter' }) | (Wizard & { __typename: 'Wizard' });
    };
    
    export type ResolversTypes = {
      // other types...
      CharacterNode: ResolverTypeWrapper<ResolversInterfaceTypes<ResolversTypes>['CharacterNode']>;
      Fighter: ResolverTypeWrapper<Fighter>;
      Wizard: ResolverTypeWrapper<Wizard>;
      // other types...
    };
    
    export type ResolversParentTypes = {
      // other types...
      CharacterNode: ResolversInterfaceTypes<ResolversParentTypes>['CharacterNode'];
      Fighter: Fighter;
      Wizard: Wizard;
      // other types...
    };
    

Patch Changes

@graphql-codegen/[email protected]

Major Changes

  • bb66c2a31 Thanks @n1ru4l! - Require Node.js >= 16. Drop support for Node.js 14

Minor Changes

  • #9196 3848a2b73 Thanks @beerose! - Add @defer directive support

    When a query includes a deferred fragment field, the server will return a partial response with the non-deferred fields first, followed by the remaining fields once they have been resolved.

    Once start using the @defer directive in your queries, the generated code will automatically include support for the directive.

    // src/index.tsx
    import { graphql } from './gql';
    const OrdersFragment = graphql(`
      fragment OrdersFragment on User {
        orders {
          id
          total
        }
      }
    `);
    const GetUserQuery = graphql(`
      query GetUser($id: ID!) {
        user(id: $id) {
          id
          name
          ...OrdersFragment @defer
        }
      }
    `);
    

    The generated type for GetUserQuery will have information that the fragment is incremental, meaning it may not be available right away.

    // gql/graphql.ts
    export type GetUserQuery = { __typename?: 'Query'; id: string; name: string } & ({
      __typename?: 'Query';
    } & {
      ' $fragmentRefs'?: { OrdersFragment: Incremental<OrdersFragment> };
    });
    

    Apart from generating code that includes support for the @defer directive, the Codegen also exports a utility function called isFragmentReady. You can use it to conditionally render components based on whether the data for a deferred
    fragment is available:

    const OrdersList = (props: { data: FragmentType<typeof OrdersFragment> }) => {
      const data = useFragment(OrdersFragment, props.data);
      return (
        // render orders list
      )
    };
    
    function App() {
      const { data } = useQuery(GetUserQuery);
      return (
        {data && (
          <>
            {isFragmentReady(GetUserQuery, OrdersFragment, data)
    					&& <OrdersList data={data} />}
          </>
        )}
      );
    }
    export default App;
    

Patch Changes

@graphql-codegen/[email protected]

Major Changes

  • #9375 ba84a3a27 Thanks @eddeee888! - Implement Scalars with input/output types

    In GraphQL, Scalar types can be different for client and server. For example, given the native GraphQL ID:

    • A client may send string or number in the input
    • A client receives string in its selection set (i.e output)
    • A server receives string in the resolver (GraphQL parses string or number received from the client to string)
    • A server may return string or number (GraphQL serializes the value to string before sending it to the client )

    Currently, we represent every Scalar with only one type. This is what codegen generates as base type:

    export type Scalars = {
      ID: string;
    };
    

    Then, this is used in both input and output type e.g.

    export type Book = {
      __typename?: 'Book';
      id: Scalars['ID']; // Output's ID can be `string` 👍
    };
    
    export type QueryBookArgs = {
      id: Scalars['ID']; // Input's ID can be `string` or `number`. However, the type is only `string` here 👎
    };
    

    This PR extends each Scalar to have input and output:

    export type Scalars = {
      ID: {
        input: string | number;
        output: string;
      };
    };
    

    Then, each input/output GraphQL type can correctly refer to the correct input/output scalar type:

    export type Book = {
      __typename?: 'Book';
      id: Scalars['ID']['output']; // Output's ID can be `string` 👍
    };
    
    export type QueryBookArgs = {
      id: Scalars['ID']['input']; // Input's ID can be `string` or `number` 👍
    };
    

    Note that for typescript-resolvers, the type of ID needs to be inverted. However, the referenced types in GraphQL input/output types should still work correctly:

    export type Scalars = {
      ID: {
        input: string;
        output: string | number;
      }
    }
    
    export type Book = {
      __typename?: "Book";
      id: Scalars["ID"]['output']; // Resolvers can return `string` or `number` in ID fields 👍
    };
    
    export type QueryBookArgs = {
      id: Scalars["ID"]['input']; // Resolvers receive `string` in ID fields 👍
    };
    
    export type ResolversTypes = {
      ID: ID: ResolverTypeWrapper<Scalars['ID']['output']>; // Resolvers can return `string` or `number` in ID fields 👍
    }
    
    export type ResolversParentTypes = {
      ID: Scalars['ID']['output']; // Resolvers receive `string` or `number` from parents 👍
    };
    

    Config changes:

    1. Scalars option can now take input/output types:
    config: {
      scalars: {
        ID: {
          input: 'string',
          output: 'string | number'
        }
      }
    }
    
    1. If a string is given (instead of an object with input/output fields), it will be used as both input and output types:
    config: {
      scalars: {
        ID: 'string'; // This means `string` will be used for both ID's input and output types
      }
    }
    
    1. BREAKING CHANGE: External module Scalar types need to be an object with input/output fields
    config: {
      scalars: {
        ID: './path/to/scalar-module';
      }
    }
    

    If correctly, wired up, the following will be generated:

    // Previously, imported `ID` type can be a primitive type, now it must be an object with input/output fields
    import { ID } from './path/to/scalar-module';
    
    export type Scalars = {
      ID: { input: ID['input']; output: ID['output'] };
    };
    

    BREAKING CHANGE: This changes Scalar types which could be referenced in other plugins. If you are a plugin maintainer and reference Scalar, please update your plugin to use the correct input/output types.

  • bb66c2a31 Thanks @n1ru4l! - Require Node.js >= 16. Drop support for Node.js 14

Minor Changes

  • #9196 3848a2b73 Thanks @beerose! - Add @defer directive support

    When a query includes a deferred fragment field, the server will return a partial response with the non-deferred fields first, followed by the remaining fields once they have been resolved.

    Once start using the @defer directive in your queries, the generated code will automatically include support for the directive.

    // src/index.tsx
    import { graphql } from './gql';
    const OrdersFragment = graphql(`
      fragment OrdersFragment on User {
        orders {
          id
          total
        }
      }
    `);
    const GetUserQuery = graphql(`
      query GetUser($id: ID!) {
        user(id: $id) {
          id
          name
          ...OrdersFragment @defer
        }
      }
    `);
    

    The generated type for GetUserQuery will have information that the fragment is incremental, meaning it may not be available right away.

    // gql/graphql.ts
    export type GetUserQuery = { __typename?: 'Query'; id: string; name: string } & ({
      __typename?: 'Query';
    } & {
      ' $fragmentRefs'?: { OrdersFragment: Incremental<OrdersFragment> };
    });
    

    Apart from generating code that includes support for the @defer directive, the Codegen also exports a utility function called isFragmentReady. You can use it to conditionally render components based on whether the data for a deferred
    fragment is available:

    const OrdersList = (props: { data: FragmentType<typeof OrdersFragment> }) => {
      const data = useFragment(OrdersFragment, props.data);
      return (
        // render orders list
      )
    };
    
    function App() {
      const { data } = useQuery(GetUserQuery);
      return (
        {data && (
          <>
            {isFragmentReady(GetUserQuery, OrdersFragment, data)
    					&& <OrdersList data={data} />}
          </>
        )}
      );
    }
    export default App;
    
  • #9304 e1dc75f3c Thanks @esfomeado! - Added support for disabling suffixes on Enums.

Patch Changes

@graphql-codegen/[email protected]

Major Changes

  • bb66c2a31 Thanks @n1ru4l! - Require Node.js >= 16. Drop support for Node.js 14

Minor Changes

  • #9196 3848a2b73 Thanks @beerose! - Add @defer directive support

    When a query includes a deferred fragment field, the server will return a partial response with the non-deferred fields first, followed by the remaining fields once they have been resolved.

    Once start using the @defer directive in your queries, the generated code will automatically include support for the directive.

    // src/index.tsx
    import { graphql } from './gql';
    const OrdersFragment = graphql(`
      fragment OrdersFragment on User {
        orders {
          id
          total
        }
      }
    `);
    const GetUserQuery = graphql(`
      query GetUser($id: ID!) {
        user(id: $id) {
          id
          name
          ...OrdersFragment @defer
        }
      }
    `);
    

    The generated type for GetUserQuery will have information that the fragment is incremental, meaning it may not be available right away.

    // gql/graphql.ts
    export type GetUserQuery = { __typename?: 'Query'; id: string; name: string } & ({
      __typename?: 'Query';
    } & {
      ' $fragmentRefs'?: { OrdersFragment: Incremental<OrdersFragment> };
    });
    

    Apart from generating code that includes support for the @defer directive, the Codegen also exports a utility function called isFragmentReady. You can use it to conditionally render components based on whether the data for a deferred
    fragment is available:

    const OrdersList = (props: { data: FragmentType<typeof OrdersFragment> }) => {
      const data = useFragment(OrdersFragment, props.data);
      return (
        // render orders list
      )
    };
    
    function App() {
      const { data } = useQuery(GetUserQuery);
      return (
        {data && (
          <>
            {isFragmentReady(GetUserQuery, OrdersFragment, data)
    					&& <OrdersList data={data} />}
          </>
        )}
      );
    }
    export default App;
    
  • #9353 d7e335b58 Thanks @charpeni! - Implement the ability the specify the hash algorithm used for persisted documents via persistedDocuments.hashAlgorithm

Patch Changes

@graphql-codegen/[email protected]

Major Changes

  • bb66c2a31 Thanks @n1ru4l! - Require Node.js >= 16. Drop support for Node.js 14

Patch Changes

@graphql-codegen/[email protected]

Major Changes

  • bb66c2a31 Thanks @n1ru4l! - Require Node.js >= 16. Drop support for Node.js 14

Patch Changes

@graphql-codegen/[email protected]

Major Changes

  • bb66c2a31 Thanks @n1ru4l! - Require Node.js >= 16. Drop support for Node.js 14

Patch Changes

graphql-code-generator - April 22, 2023

Published by theguild-bot over 1 year ago

@graphql-codegen/[email protected]

Patch Changes

  • #9267 183749346 Thanks @milesrichardson! - Fix watch mode to listen to longest common directory prefix of relevant files, rather than only files below the current working directory (fixes #9266).

  • #9280 ca1d72c40 Thanks @saihaj! - fix the default output directory for init command

@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-code-generator - April 04, 2023

Published by theguild-bot over 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
graphql-code-generator - March 07, 2023

Published by theguild-bot over 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

graphql-code-generator - February 23, 2023

Published by theguild-bot over 1 year ago

@graphql-cli/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Patch Changes

graphql-code-generator - February 22, 2023

Published by theguild-bot over 1 year ago

@graphql-cli/[email protected]

Patch Changes

@graphql-codegen/[email protected]

Minor Changes

Patch Changes

graphql-code-generator - February 21, 2023

Published by n1ru4l over 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

graphql-code-generator - February 03, 2023

Published by github-actions[bot] over 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

graphql-code-generator - January 30, 2023

Published by github-actions[bot] over 1 year ago

@graphql-codegen/[email protected]

Patch Changes

graphql-code-generator - January 30, 2023

Published by github-actions[bot] over 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

graphql-code-generator - January 10, 2023

Published by github-actions[bot] almost 2 years 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

graphql-code-generator - January 04, 2023

Published by github-actions[bot] almost 2 years 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