GraphQL Codegen for Dart
repository·main·Indexed 41 days ago
https://github.com/heftapp/graphql_codegenA 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.
What's inside GraphQL Codegen
- 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.
Use the graphql_codegen package for code generation
mainTo generate type-safe Dart classes for your GraphQL operations, you should use thegraphql_codegenpackage. This package acts as a build runner that processes your GraphQL files and generates the corresponding Dart code.Configure GraphQL Codegen clients
mainThe
clientssetting determines which code generation targets are active. You can specify one or more clients from the following options:graphql: Standard GraphQL client generation.graphql_flutter: Generation specifically optimized forgraphql_flutter.
{ "clients": ["graphql"] }Configure custom Scalar types
mainUse the
scalarsmap to map GraphQL scalar names to specific Dart types and import locations. This is useful for handling custom scalars likeDateTimeorUUID.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" } } }Configure custom Enum types
mainUse the
enumsmap 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" } } }Handle GraphQL printing errors
mainIf an error occurs during the process of printing a GraphQL document, a
PrinterErroris thrown. This typically indicates an issue when converting internal representations back into a GraphQL string format.try { // code that performs GraphQL printing } on PrinterError catch (e) { print(e.message); }Handle GraphQL document parsing errors
mainIf 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); }Generate code using the generate() function
mainThe
generatefunction is the primary entry point for programmatically generating Dart code from GraphQL documents. It takes a key representing the target, aSchemaConfigcontaining your GraphQL documents, and aGraphQLCodegenConfigfor settings like clients and scalars.To use it, you must provide a
SchemaConfigwhich maps keys toDocumentNodeentries and includes alookupPathfunction to resolve paths from those keys.// Example usage pattern Library generate<TKey extends Object>( TKey key, SchemaConfig<TKey> schemaConfig, GraphQLCodegenConfig config, )Configure codegen settings with GraphQLCodegenConfig
mainTheGraphQLCodegenConfigobject is passed to the generation process to provide global configuration settings. This typically includes definitions for custom scalars and client configurations used during the code generation lifecycle.Configure the schema with SchemaConfig
mainThe
SchemaConfig<TKey>class is used to define the collection of GraphQL documents available for code generation. It requires two main components:entries: ABuiltMap<TKey, DocumentNode>where each key is associated with a GraphQL document node.lookupPath: A functionString Function(TKey)used to look up a file path from a given key.
The class also includes a
mainKeygetter 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", );Configure the GraphQLBuilder for build_runner
mainThe
GraphQLBuilderis the primary entrypoint for integrating GraphQL code generation into a Dart project usingbuild_runner. It is initialized via thebuilderstatic method, which acceptsBuilderOptions. The configuration for the generation process is passed through theconfigproperty withinBuilderOptionsand is parsed into aGraphQLCodegenConfigobject.To use this in a
build.yamlfile, you would reference thebuildermethod 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"Supported GraphQL file extensions
mainThe
GraphQLBuildermonitors and processes files with the following extensions:.graphql.graphqls.gql
const kGraphQLFileExtensions = ['graphql', 'graphqls', 'gql'];