-
Notifications
You must be signed in to change notification settings - Fork 134
/
LocalDateTime.ts
76 lines (72 loc) · 2.17 KB
/
LocalDateTime.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { ASTNode, GraphQLScalarType, GraphQLScalarTypeConfig, Kind } from 'graphql';
import { createGraphQLError } from '../error.js';
const LOCAL_DATE_TIME_REGEX =
/^((?:(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2}(?:\.\d+)?))(Z|[\+-]\d{2}:\d{2})?)$/;
function validateLocalDateTime(value: any, ast?: ASTNode): string {
if (typeof value !== 'string') {
throw createGraphQLError(
`Value is not string: ${value}`,
ast
? {
nodes: [ast],
}
: undefined,
);
}
if (!LOCAL_DATE_TIME_REGEX.test(value.toUpperCase())) {
throw createGraphQLError(
`LocalDateTime cannot represent an invalid local date-time-string ${value}.`,
ast
? {
nodes: [ast],
}
: undefined,
);
}
const valueAsDate = new Date(value);
const isValidDate = !isNaN(valueAsDate.getTime());
if (!isValidDate) {
throw createGraphQLError(
`Value is not a valid LocalDateTime: ${value}`,
ast
? {
nodes: [ast],
}
: undefined,
);
}
return value;
}
export const LocalDateTimeConfig: GraphQLScalarTypeConfig<string, string> = /*#__PURE__*/ {
name: 'LocalDateTime',
description:
'A local date-time string (i.e., with no associated timezone) in `YYYY-MM-DDTHH:mm:ss` format, e.g. `2020-01-01T00:00:00`.',
serialize(value) {
return validateLocalDateTime(value);
},
parseValue(value) {
return validateLocalDateTime(value);
},
parseLiteral(ast) {
if (ast.kind !== Kind.STRING) {
throw createGraphQLError(
`Can only validate strings as local date-times but got a: ${ast.kind}`,
{
nodes: [ast],
},
);
}
return validateLocalDateTime(ast.value, ast);
},
extensions: {
codegenScalarType:
// eslint-disable-next-line no-template-curly-in-string
'`${number}${number}${number}${number}-${number}${number}-${number}${number}T${number}${number}:${number}${number}:${number}${number}`',
jsonSchema: {
title: 'LocalDateTime',
type: 'string',
format: 'date-time',
},
},
};
export const GraphQLLocalDateTime = /*#__PURE__*/ new GraphQLScalarType(LocalDateTimeConfig);