forked from canada-ca/tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyear.js
More file actions
30 lines (25 loc) · 728 Bytes
/
year.js
File metadata and controls
30 lines (25 loc) · 728 Bytes
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
import { GraphQLScalarType, Kind, GraphQLError } from 'graphql'
const validate = (value) => {
const YEAR_REGEX = /^\d{4}$/
if (typeof value !== 'string') {
throw new TypeError(`Value is not string: ${typeof value}`)
}
if (!YEAR_REGEX.test(value)) {
throw new TypeError(`Value is not a valid year: ${value}`)
}
return value
}
export const Year = new GraphQLScalarType({
name: 'Year',
description: 'A field that conforms to a 4 digit integer.',
serialize: validate,
parseValue: validate,
parseLiteral(ast) {
if (ast.kind !== Kind.STRING) {
throw new GraphQLError(
`Can only validate strings as year but got a: ${ast.kind}`,
)
}
return validate(ast.value)
},
})