GraphQL Custom scalar type DateScalar

Viewed 25

This is my Resolvers, typedefs and dateScalar file. I am in the process of creating a custom scalar Date to represent Date for an object when querying through GraphQL.

resolvers.js

const dateScalar = require("./dateScalar");
const resolvers = {

  DateScalar: {
    dateScalar,
  },
};

module.exports = resolvers;

dateScalar.js

module.exports = {
DateScalar: new GraphQLScalarType({
name: "DateScalar",
description: "Date Scalar type",

parseValue(value) {
  return new Date(value);
},
parseLiteral(ast) {
  if (ast.kind === Kind.INT) {
    // return parseInt(ast.value, 10);
    return new Date(ast.value);
  }
  return null;
},
serialize(value) {
  // const date = new Date(value);
  // return date.toISOString();
  return value.getTime();
},
}),
};

typeDef.js

const {gql} = require("apollo-server-express);
const typeDefs = gql`
scalar DateScalar
type Item{
Date: DateScalar
 } `
1 Answers

This is literally the example in the Apollo Docs. You have to pass the dateScalar directly to DateScalar and not pun the property:

const resolvers = {
  DateScalar: dateScalar,
};
Related