Advanced
Creating Custom Scalars
SwiftGraphQL by default encodes all fields that reference unconfigured scalars as AnyCodable
values. For easier decoding and better type support you can, however, create custom GraphQLScalar
structures.
To create a custom scalar, you need to create a structure that conforms to the GraphQLScalar
protocol.
It doesn’t matter where you implement the conformance as long as it’s in the same project as the generated code.
Because GraphQLScalar
uses the Encodable
protocol to encode the value, you might need to customize how JSONEncoder
encodes the built-in value in case you are mapping a custom scalar to a built-in type. Depending on your target, you should either
- pass a custom
JSONEncoder
as a paramater to theURLRequest.query
method, - provide a custom
encoder
toFetchExchange
- modify the
encoder
inGraphQLWebSocketConfiguration
.
Example DateTime Scalar
Don’t forget to add your scalar mapping to code generator options!