Created
November 28, 2016 20:31
-
-
Save wmertens/bc5cb362cb257074df6853b7e4f96227 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Based on https://gist.github.com/langpavel/b30f3d507a47713b0c6e89016e4e9eb7 | |
const serializeDate = value => { | |
if (value instanceof Date) { | |
return value.toJSON().slice(0, 10) | |
} else if (typeof value === 'number') { | |
return Math.trunc(value) | |
} else if (typeof value === 'string') { | |
return (new Date(value)).toJSON().slice(0, 10) | |
} | |
return null | |
} | |
const parseDate = value => { | |
if (value == null) {return null} | |
try { | |
return new Date(value) | |
} catch (err) { | |
return null | |
} | |
} | |
const parseDateFromLiteral = ast => { | |
if (ast.kind === Kind.INT) { | |
return parseDate(Number(ast.value)) | |
} else if (ast.kind === Kind.STRING) { | |
return parseDate(ast.value) | |
} | |
return null | |
} | |
export const DateType = new GraphQLScalarType({ | |
name: 'Date', | |
description: | |
'A date without time (or timezone)', | |
serialize: serializeDate, | |
parseValue: parseDate, | |
parseLiteral: parseDateFromLiteral, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment