-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathdatetype.js
49 lines (44 loc) · 1.37 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { GraphQLScalarType } from 'graphql'
import { GraphQLError } from 'graphql/error'
import { Kind } from 'graphql/language'
function parseDate (value) {
let result = new Date(value)
if (isNaN(result.getTime())) {
throw new TypeError('Invalid date: ' + value)
}
if (value !== result.toJSON()) {
throw new TypeError('Invalid date format, only accepts: YYYY-MM-DDTHH:MM:SS.SSSZ: ' + value)
}
return result
}
export default new GraphQLScalarType({
name: 'DateTime',
// Serialize a date to send to the client.
serialize (value) {
if (!(value instanceof Date)) {
throw new TypeError('Field error: value is not an instance of Date')
}
if (isNaN(value.getTime())) {
throw new TypeError('Field error: value is an invalid Date')
}
return value.toJSON()
},
// Parse a date received as a query variable.
parseValue (value) {
if (typeof value !== 'string') {
throw new TypeError('Field error: value is not an instance of string')
}
return parseDate(value)
},
// Parse a date received as an inline value.
parseLiteral (ast) {
if (ast.kind !== Kind.STRING) {
throw new GraphQLError('Query error: Can only parse strings to dates but got a: ' + ast.kind, [ast])
}
try {
return parseDate(ast.value)
} catch (e) {
throw new GraphQLError('Query error: ' + e.message, [ast])
}
}
})