forked from soundtrackyourbrand/graphql-custom-datetype
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatetype.js
33 lines (31 loc) · 1.02 KB
/
datetype.js
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
import { GraphQLScalarType } from 'graphql'
import { GraphQLError } from 'graphql/error'
import { Kind } from 'graphql/language'
function coerceDate (value) {
if (!(value instanceof Date)) {
// Is this how you raise a 'field error'?
throw new Error('Field error: value is not an instance of Date')
}
if (isNaN(value.getTime())) {
throw new Error('Field error: value is an invalid Date')
}
return value.toJSON()
}
export default new GraphQLScalarType({
name: 'DateTime',
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])
}
let result = new Date(ast.value)
if (isNaN(result.getTime())) {
throw new GraphQLError('Query error: Invalid date', [ast])
}
if (ast.value !== result.toJSON()) {
throw new GraphQLError('Query error: Invalid date format, only accepts: YYYY-MM-DDTHH:MM:SS.SSSZ', [ast])
}
return result
}
})