Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposed plugin: Custom Scalar helper #366

Closed
frec-kenneth opened this issue Jun 23, 2023 · 1 comment
Closed

Proposed plugin: Custom Scalar helper #366

frec-kenneth opened this issue Jun 23, 2023 · 1 comment

Comments

@frec-kenneth
Copy link

Custom Scalar support is important for many projects. GraphQL only natively supports ID, String, Int, Float, and Boolean. Significantly missing is Date/DateTime. We are also using BigInt, Decimal.js and DateOnly (without a time). Apollo Server has good support for serializing and deserializing custom scalars, but that feature is missing from the client.

The key to implementation in the client is knowing which fields are of the custom type. One workaround is to serialize the field on the server as a more complex type with a __typename attribute. We can then use ApolloLink to deserialize on the client. While a little verbose over the wire, this works quite well, except in systems that don't use ApolloLink (eg, we're using Retool which appears to have no support for a global transformer). We often want to serialize the field as a simple string, and then somehow know which fields should be deserialized.

A documented solution to this problem is to use type policies in the Apollo cache configuration. For each field, we can specify a "read" method which could deserialize. However, there is no way to programmatically know which fields we should specify, and doing this by hand is brittle.

I propose a plugin for codegen which outputs a list of fields and types for our custom scalars.

A possible implementation is on my fork at:
https://github.com/frec-kenneth/graphql-code-generator-community/tree/kenneth/custom-scalar-usage/packages/plugins/typescript/custom-scalar-usage

As shown in the spec, for a given schema:

      scalar DateTime
      type User {
        id: ID!
        creationDate: DateTime!
        logins: [DateTime]
      }

this will output a const

export const scalarUsage = {
  "DateTime": {
    "User": [
      "creationDate",
      "logins"
    ]
  },
}

and then we can use the scalarUsage in our cache config to output all the typepolicies that are needed to deserialize the fields.

Thanks for your consideration.

@frec-kenneth frec-kenneth changed the title Custom Scalar helper Proposed plugin: Custom Scalar helper Jun 23, 2023
@frec-kenneth
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant