GraphQL Codegen for Dart

repository·main·Indexed 41 days ago

https://github.com/heftapp/graphql_codegen

A tool for generating type-safe Dart classes from GraphQL schemas and documents. It integrates with build_runner via GraphQLBuilder to process .graphql, .graphqls, and .gql files, reducing runtime errors by mapping GraphQL operations directly to Dart types. Supports custom scalar and enum mapping, and provides specific generation targets for standard GraphQL and graphql_flutter clients.

Tokens
2.1K
Snippets
9
Records
13
Agent score
100%

What's inside GraphQL Codegen

  1. Overview of GraphQL Codegen for Dart

    main
    GraphQL Codegen is a tool designed for the Dart ecosystem that automates the creation of type-safe Dart classes from your GraphQL operations. This ensures that your GraphQL queries, mutations, and schema definitions are mapped directly to Dart types, reducing runtime errors and improving developer productivity through strong typing.
  2. Use the graphql_codegen package for code generation

    main
    To generate type-safe Dart classes for your GraphQL operations, you should use the graphql_codegen package. This package acts as a build runner that processes your GraphQL files and generates the corresponding Dart code.
  3. Configure custom Scalar types

    main

    Use the scalars map to map GraphQL scalar names to specific Dart types and import locations. This is useful for handling custom scalars like DateTime or UUID.

    Each scalar configuration includes:

    • type: The Dart type name.
    • import: The library import path containing the type.
    • fromJsonFunctionName: (Optional) Custom name for the JSON deserialization function.
    • toJsonFunctionName: (Optional) Custom name for the JSON serialization function.
    {
      "scalars": {
        "DateTime": {
          "type": "DateTime",
          "import": "package:intl/intl.dart"
        }
      }
    }
  4. Configure custom Enum types

    main

    Use the enums map to map GraphQL enums to existing Dart enums. This prevents the generator from creating duplicate enum classes.

    Each enum configuration includes:

    • type: The Dart enum type name.
    • import: The library import path containing the enum.
    • fromJsonFunctionName: (Optional) Custom name for the JSON deserialization function.
    • toJsonFunctionName: (Optional) Custom name for the JSON serialization function.
    • fallbackEnumValue: The value to use if the incoming JSON value does not match any known enum member.
    {
      "enums": {
        "UserRole": {
          "type": "UserRole",
          "import": "package:my_app/models/roles.dart",
          "fallbackEnumValue": "unknown"
        }
      }
    }
  5. Handle GraphQL document parsing errors

    main

    If the GraphQL document being processed is malformed, missing type definitions, or contains missing fields, the library throws an InvalidGraphQLDocumentError. You can catch this error to identify issues in your schema or query definitions. The error message provides details about the specific parsing failure.

    try {
      // code that performs GraphQL parsing or codegen
    } on InvalidGraphQLDocumentError catch (e) {
      print(e.message);
    }
  6. Generate code using the generate() function

    main

    The generate function is the primary entry point for programmatically generating Dart code from GraphQL documents. It takes a key representing the target, a SchemaConfig containing your GraphQL documents, and a GraphQLCodegenConfig for settings like clients and scalars.

    To use it, you must provide a SchemaConfig which maps keys to DocumentNode entries and includes a lookupPath function to resolve paths from those keys.

    // Example usage pattern
    Library generate<TKey extends Object>(
      TKey key,
      SchemaConfig<TKey> schemaConfig,
      GraphQLCodegenConfig config,
    )
  7. Configure the schema with SchemaConfig

    main

    The SchemaConfig<TKey> class is used to define the collection of GraphQL documents available for code generation. It requires two main components:

    1. entries: A BuiltMap<TKey, DocumentNode> where each key is associated with a GraphQL document node.
    2. lookupPath: A function String Function(TKey) used to look up a file path from a given key.

    The class also includes a mainKey getter that automatically attempts to identify the primary schema key by inspecting operation types (Query, Mutation, Subscription) within the provided entries.

    SchemaConfig<TKey>(
      entries: myEntriesMap, // BuiltMap<TKey, DocumentNode>
      lookupPath: (key) => "path/to/file_$key.graphql",
    );
  8. Configure the GraphQLBuilder for build_runner

    main

    The GraphQLBuilder is the primary entrypoint for integrating GraphQL code generation into a Dart project using build_runner. It is initialized via the builder static method, which accepts BuilderOptions. The configuration for the generation process is passed through the config property within BuilderOptions and is parsed into a GraphQLCodegenConfig object.

    To use this in a build.yaml file, you would reference the builder method provided by this package.

    # Example build.yaml usage
    builders:
      graphql_codegen:graphql_builder:
        import: "package:graphql_codegen/builder.dart"
        builder: GraphQLBuilder.builder
        options:
          config:
            # GraphQLCodegenConfig properties go here
            assetsPath: "lib/graphql"
            outputDirectory: "lib/generated"