'How can I define Date data type in Graphql schema? [duplicate]
Solution 1:[1]
You can use a custom scallar that parse the Int into date If you are using apollo server you can try something like this
import { GraphQLScalarType } from 'graphql';
import { Kind } from 'graphql/language';
const resolverMap = {
Date: new GraphQLScalarType({
name: 'Date',
description: 'Date custom scalar type',
parseValue(value) {
return new Date(value); // value from the client
},
serialize(value) {
return value.getTime(); // value sent to the client
},
parseLiteral(ast) {
if (ast.kind === Kind.INT) {
return new Date(ast.value) // ast value is always in string format
}
return null;
},
}),
};
And then
scalar Date
type MyType {
created: Date
}
You can take a closer look here https://www.apollographql.com/docs/graphql-tools/scalars/ Here are some other useful scalars https://github.com/Urigo/graphql-scalars
Solution 2:[2]
Long answer: you should define a scalar type to represent your date information (as documented and also answered)
Short answer: you may use a 3rd party lib to take care for you (such as https://www.npmjs.com/package/graphql-iso-date (you use node so this one should suit your needs)
Either way, I assume the numeric value is a timestamp so you should use the resolve function to translate this numuber to a valid date
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Esteban Torres |
| Solution 2 |

