/
Date.ts
37 lines (35 loc) · 1.33 KB
/
Date.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { GraphQLScalarType } from "graphql";
import { GraphQLError } from "graphql/error";
import { Kind } from "graphql/language";
function coerceDate(value: any) {
if (!(value instanceof Date)) {
// Is this how you raise a 'field error'?
// throw new Error("Field error: value is not an instance of Date");
value = new Date(value);
}
if (isNaN(value.getTime())) {
throw new Error("Field error: value is an invalid Date");
}
return value.toUTCString();
}
export default new GraphQLScalarType({
name: "Date",
description: "Date",
serialize: coerceDate,
parseValue: coerceDate,
parseLiteral(ast) {
if (ast.kind !== Kind.STRING) {
throw new GraphQLError("Query error: Can only parse strings to dates but got a: " + ast.kind, [ast]);
}
const result = new Date(ast.value);
if (isNaN(result.getTime())) {
throw new GraphQLError("Query error: Invalid date " + ast.value, [ast]);
}
if (ast.value !== result.toJSON() && ast.value !== result.toUTCString() && ast.value !== result.toString()) {
throw new GraphQLError("Query error: Invalid date format " +
ast.value
+ " , only accepts: YYYY-MM-DDTHH:MM:SS.SSSZ or UTC or local UTC", [ast]);
}
return result;
},
});