I am building a GraphQL schema programmatically and in need of a Timestamp
scalar type; a Unix Epoch timestamp scalar type:
const TimelineType = new GraphQLObjectType({
name: 'TimelineType',
fields: () => ({
date: { type: new GraphQLNonNull(GraphQLTimestamp) },
price: { type: new GraphQLNonNull(GraphQLFloat) },
sold: { type: new GraphQLNonNull(GraphQLInt) }
})
});
Unfortunately, GraphQL.js doesn't have a GraphQLTimestamp
nor a GraphQLDate
type so the above doesn't work.
I am expecting a Date
input and I want to convert that to a timestamp. How would I go about creating my own GraphQL timestamp type?
GraphQL's Scalar TypesInt: A signed 32‐bit integer. Float: A signed double-precision floating-point value. String: A UTF‐8 character sequence. Boolean: true or false. ID: The ID scalar type represents a unique identifier, often used to refetch an object or as the key for a cache.
The GraphQL specification includes default scalar types Int , Float , String , Boolean , and ID . Although these scalars cover the majority of use cases, some applications need to support other atomic data types (such as Date ) or add validation to an existing type. To enable this, you can define custom scalar types.
GraphQL comes with default scalar types like Int, Float, String, Boolean and ID. But dates and times have to be defined as custom scalars like Date or timestamp etc.
const server = new ApolloServer({ typeDefs, resolvers: { Date: dateScalar, // Remaining resolvers.. }, }); This Date implementation will parse any string accepted by the Date constructor, and will return the date as a string in ISO format. For JSON you might use graphql-type-json and import it as shown here.
There is an NPM package with a set of RFC 3339 compliant date/time GraphQL scalar types; graphql-iso-date.
But for starters, You should use GraphQLScalarType
to build your own scalar type in GraphQL programmatically:
/** Kind is an enum that describes the different kinds of AST nodes. */
import { Kind } from 'graphql/language';
import { GraphQLScalarType } from 'graphql';
const TimestampType = new GraphQLScalarType({
name: 'Timestamp',
serialize(date) {
return (date instanceof Date) ? date.getTime() : null
},
parseValue(date) {
try { return new Date(value); }
catch (error) { return null; }
},
parseLiteral(ast) {
if (ast.kind === Kind.INT) {
return new Date(parseInt(ast.value, 10));
}
else if (ast.kind === Kind.STRING) {
return this.parseValue(ast.value);
}
else {
return null;
}
},
});
But instead of re-inventing the wheel, this issue (#550) was already discussed and Pavel Lang came up with a decent GraphQLTimestamp.js solution (my TimestampType
is derived from his).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With