If our GraphQL schema includes custom
scalar types, we'll need to configure Ferry's code generator to properly handle them.
Let's say our GraphQL schema includes a
Date scalar that we want to map to Dart's
Configure Type Overrides
Specifying a Type Overrides tells the generator what Dart types to use when generating a type from our GraphQL schema (in this case our custom
The key in the yaml Map should be the name of our custom scalar in our schema (i.e. "Date"), and
name should be the name of the Dart type.
We've included only the
schema_builder above for brevity, but we will need to include this same type_overrides map for
req_builder as well. See the complete build.yaml example for more details.
If our Dart type is not part of the
dart:core library, we'd also need to import the file that contains the Dart type. DateTime is a part of
dart:core, but if it weren't, we'd import it like so:
Configure Custom Serializer
If our Dart type is not a Dart Data Type, we also need to define a custom serializer so that the generated classes can be correctly serialized & deserialized the data.
Assuming we've created a
DateSerializer for our custom
Date scalar, we will need to include it in our
Here's an example of what our final
build.yaml might look like.
Create a Custom Serializer
In order for us to instantiate our generated Dart Classes with data from our GraphQL server, we will need to create a custom
built_value serializer for our custom
In this case, let's assume that our GraphQL server will return our
Date scalar as an
And that's it! Now when we run our
pub run build_runner build command, ferry's generators will automatically override our GraphQL
Date scalar with the Dart
DateTime type and use our
DateSerializer to serialize & deserialize data.
We've implemented the above
DateSerializer using the
built_value. However, if we were building a serializer for a non-primitive Dart type, we'd probably want to use the
built_value doesn't use standard Json by default, rather than implementing
StructuredSerializer directly, we may prefer to extend the
gql_code_builder. For example, here's a serializer for the
Operation type from
gql_exec that ferry's generaters use internally.
For more information about serialization using
built_value, check out this blog post.