add custom DateTime scalar type

This commit is contained in:
2025-04-29 16:46:55 -07:00
parent bdb1da0bc4
commit ba82ce9f98
3 changed files with 33 additions and 1 deletions

28
src/scalars/DateTime.ts Normal file
View File

@@ -0,0 +1,28 @@
import { GraphQLScalarType } from "graphql/type";
import { Kind } from "graphql/language";
// See Apollo documentation: https://www.apollographql.com/docs/apollo-server/schema/custom-scalars#providing-custom-scalars-to-apollo-server
export const DateTime = new GraphQLScalarType({
name: 'DateTime',
description: 'DateTime custom scalar type',
serialize(value) {
if (value instanceof Date) {
return value.getTime();
} else if (value instanceof Number) {
return value;
}
throw Error('GraphQL Date Scalar serializer expected a `Date` object or number');
},
parseValue(value) {
if (typeof value === 'number') {
return new Date(value);
}
throw new Error('GraphQL Date Scalar parser expected a `number`');
},
parseLiteral(ast) {
if (ast.kind === Kind.INT) {
return new Date(parseInt(ast.value, 10));
}
return null;
},
})