How to map a custom scalar type to a typescript type when using graphql code generator?
Asked Answered
J

1

9

A custom scalar type named Date which is an ISO 8601 string is defined in the backend.

In the frontend "GraphQL Code Generator" (https://www.graphql-code-generator.com/) is used to generate typescript types from the schema.

The codegen.yml looks like this:

overwrite: true
schema: 'http://mybackenurl/graphql'
documents: 'src/**/*.graphql'
generates:
    src/generated/graphql.ts:
        config:
            exposeQueryKeys: true
            exposeFetcher: true
            fetcher: '../GraphQLFetcher#fetcher'
            scalars: 
                Date: Date
        plugins:
            - 'typescript'
            - 'typescript-operations'
            - 'typescript-react-query'

This gives types where all fields with the custom scalar type Date in the graphql schema corresponds to the typescript type Date in the generated typescript types. However at runtime it is still a string. If the part with Date: Date under scalars in the configuration is removed, the corresponding type is Any.

The guess is that we need to specify some kind of mapper which converts from the ISO 8601 string we get from the backend to a typescript Date, but I do not understand how this is can be done.

Jardena answered 1/10, 2021 at 15:30 Comment(0)
P
5

Codegen doesn't do anything for conversion, you could put Date: number and it would happily print that in your generated file. It is really just a way to automatically generate Typescript types for your API.

What you are looking for is different, you basically need a "middleware" from you graphql client that:

  1. Has access to the schema. So this means you need to be comfortable shipping your whole schema with your frontend application, which most developers are not especially for private APIs.
  2. Can parse said schema to match fields in the JSON response to scalars and then interpret them into whatever native type your want (like Date)

For the Apollo client, you can use https://github.com/eturino/apollo-link-scalars. For urql, I found https://github.com/clentfort/urql-custom-scalars-exchange.

Phonics answered 3/10, 2021 at 2:33 Comment(2)
I thought that was what resolvers could do, but I might be wrong? graphql-code-generator.com/docs/plugins/typescript-resolversJardena
Resolvers are on the backend not the frontend, your cannot transmit a Date over the wire. Everything is JSON in the end.Phonics

© 2022 - 2024 — McMap. All rights reserved.