Monday, 28 June 2021

How to resolve a GraphQL DateTime field receiving '0000-00-00' and throwing error?

I have a similar to this question, however I don't see how it could be resolved using this other syntax currently in my Apollo project. The issue is '0000-00-00' values coming from SQL db to my Apollo GraphQL server, thus throwing errors of invalid DateTime type. I'd like to write a resolver for the datetime field in question, like:

import gqlDate from 'graphql-iso-date';

const MyType = new gql.GraphQLObjectType({
  name: 'Type',
  description: 'This is a GraphQL type.',
  fields: () => {
    return {
      datetime: {
        type: gqlDate.GraphQLDateTime,
        description: 'The datetime field of my type.',
        resolve: (record) => {
          return record === '0000-00-00 00:00:00' ? null : record;
        }
      }
    };
  }
});

However I cannot adjust this example to this other syntax my project is setup to:

import { gql } from 'apollo-server'

export const schema = gql`
  extend type Query {
    users(id: ID): [User!]
  }

  type User {
    id: ID!
    first_name: String!
    middle_name: String
    birthday: String!
  }
import graphqlFields from 'graphql-fields'

export const usersResolver = {
  Query: {
    users: async (_, params, context, info) => {
      const requestedColumns = Object.keys(graphqlFields(info))
      return context.dataSources.db.getUsers(params, requestedColumns)
    },
  },
}

I played around with adding something like this to the resolver, but I'm not sure if it's the right thing to do and how exactly to implement it. Since the field resolves to Scalar, my guess is the below code won't be reached.

birthday: (parent, params, context, info) => { ... },

I also tried adding a separate query for the field, but am not sure how to connect it to the original users one.

My final resort is to just query the birthday as String and handle it on the front end, but that seems to be totally inappropriate compared to resolving it in GraphQL.



from How to resolve a GraphQL DateTime field receiving '0000-00-00' and throwing error?

No comments:

Post a Comment