graphql-zeus icon indicating copy to clipboard operation
graphql-zeus copied to clipboard

Null values being decoded by custom scalar

Open kamilJ96 opened this issue 3 years ago • 0 comments

Hello

First of all, awesome library, many thanks for this!

The graphql API we're using can return null for fields that are nullable. This, coupled with implementing a Scalar's decoder, will result in that null value going through the decoder, which can then cause issues downstream. For e.g., assuming the following schema:

type Account {
   id: ID!
   startDate: Date!
   endDate: Date
}

with the query

const scalars = ZeusScalars({
  Date: {
    decode: (e: unknown) => new Date(e as string),
  },
})
await chain('query', {scalars})({
   id: true,
   startDate: true,
   endDate: true
})

and an example response from the API being

{
   id: 123,
   startDate: "2022-01-01",
   endDate: null
}

Then both startDate and endDate values will go through the decoder, resulting in the response turning into:

{
  id: 123,
  startDate: 2022-01-01T00:00:00.000Z,
  endDate: 1970-01-01T00:00:00.000Z,
}

We can add a nullability check in the decoder itself to avoid decoding null values, like so:

decode: (e: unknown) => e == null ? e : new Date(e as string)

However now the inferred type of any Date scalar is Date | null | undefined, and so the field startDate can be potentially undefined, even though it is non-nullable, so it makes this solution less than ideal as we shouldn't need null checks for non-nullable fields.

I've scoured the docs and issues and can't see any mention of how to avoid this - it's a pretty simple change to avoid decoding null values in the library which I can raise in a PR, but any thoughts on this?

Thanks :)

kamilJ96 avatar Aug 10 '22 01:08 kamilJ96