How can you retrieve a date field in Apollo Client from a query as a Date and not a string?
Asked Answered
K

1

7

Using the following graphql:

scalar Date

type MyModel {
  id: ID!
  date: Date!
}

query MyModels {
  myModels {
    id
    date
  }
}

type Query {
  myModel: [MyModel!]
}

and resolvers:

import { DateTimeResolver } from 'graphql-scalars'
const resolvers = {
  // Scalars
  Date: DateTimeResolver,

  myModels: async () => {
    return await context.user.getMyModels()
  }
}

My query returns date: "2021-02-07T06:58:51.009Z". Is it possible to have Apollo Client convert it to a Date object instead?

Kookaburra answered 7/2, 2021 at 8:25 Comment(2)
each/all custom scalar must be de-/serialized, search github issues for possible solutions (link, field resolver)Clino
Yes, I found this library but can't get it working: github.com/eturino/apollo-link-scalars/issues/244Kookaburra
K
4

Figured it out using apollo-link-scalars:

import {
  ApolloClient,
  InMemoryCache,
  HttpLink,
  ApolloLink,
} from '@apollo/client'
import introspectionResult from 'shared/gql/generated.schema.json'
import { buildClientSchema, IntrospectionQuery } from 'graphql'
import { withScalars } from 'apollo-link-scalars'
import { DateTimeResolver } from 'graphql-scalars'

const schema = buildClientSchema(
  (introspectionResult as unknown) as IntrospectionQuery
)

const httpLink = new HttpLink({
  uri: 'http://localhost:4000',
  credentials: 'include',
})

const typesMap = {
  DateTime: DateTimeResolver,
}
const link = ApolloLink.from([
  (withScalars({ schema, typesMap }) as unknown) as ApolloLink,
  httpLink,
])

function createApolloClient() {
  return new ApolloClient({
    ssrMode: typeof window === 'undefined',
    link,
    // TODO: Save and hydrate from localStorage
    cache: new InMemoryCache(),
    // Necessary to pass the session cookie to the server on every request
    credentials: 'include',
  })
}

I looked at my generated schema and found that the scalar was being called DateTime instead of Date so I changed the typeMap to DateTime: DateTimeResolver and it's working.

Kookaburra answered 7/2, 2021 at 22:31 Comment(1)
This solution requires including the entire schema client-side which exposes data that you might want confidential. I wish there was a better solution!Mark

© 2022 - 2024 — McMap. All rights reserved.