How can I define Date data type in Graphql schema?
Solution 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
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
Related videos on Youtube
Pep
Updated on June 04, 2022Comments
-
Pep almost 2 years
I receive LASTUPDATE: 1579443364 response from an external API,
How can I define the data type in the schema in order to convert it to Date format?Like this format: Mon Jan 19 2020 00:44:04
GraphQL schema language supports:
Int
Float
String
Id
Boolean-
jonrsharpe about 4 yearsIt's not a date, it's an Int
-
Pep about 4 yearsYes, but I want to convert it into this format " Mon Jan 19 2020 00:44:04 "
-
jonrsharpe about 4 yearsHow is that anything to do with the schema, though? The schema describes the API, which in this case is an Int. if you want to parse that and e.g. store it differently, that's up to the code behind the API.
-