Last active
April 8, 2016 17:55
Defines and exports a custom GraphQL scalar type that represents date and time with a time zone, which, while serialized as a string, promises to conform to ISO‐8601 format.
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
# Defines and exports a custom GraphQL scalar type that represents date and time, | |
# which, while serialized as a string, promises to conform to ISO‐8601 format. | |
# (adapted from https://github.com/soundtrackyourbrand/graphql-custom-datetype) | |
graphql = require 'graphql' | |
graphql_language = require 'graphql/language' | |
graphql_error = require 'graphql/error' | |
GraphQLScalarType = graphql.GraphQLScalarType | |
GraphQLError = graphql_error.GraphQLError | |
Kind = graphql_language.Kind | |
console.info "SCHEMA> Declaring 'DateTime' custom GraphQL scalar type" | |
coerceAsDate = (value) -> | |
if typeof value isnt "string" | |
throw new GraphQLError( "Result coercion error: can only parse strings to dates; " + | |
"got value #{value} of type #{typeof value}") | |
result = new Date( value) | |
if( result not instanceof Date) or( isNaN result.getTime()) | |
throw new GraphQLError( "Result coercion error: value #{value} is an invalid Date") | |
return result | |
serializeDate = (value) -> | |
if value not instanceof Date | |
value = coerceAsDate value | |
return value.toJSON() | |
module.exports = new GraphQLScalarType { | |
name: "DateTime" | |
description: "Scalar type that represents date and time with a time zone, which, " + | |
"while serialized as a string, promises to conform to ISO‐8601 format." | |
serialize: serializeDate | |
parseValue: coerceAsDate | |
parseLiteral: (ast) -> | |
if ast.kind isnt Kind.STRING | |
throw new GraphQLError( "Query input coercion error: Can only parse strings to dates; " + | |
"got value #{ast.value} of kind #{ast.kind}", [ast]) | |
result = new Date( ast.value) | |
if( result not instanceof Date) or( isNaN result.getTime()) | |
throw new GraphQLError( "Query input coercion error: value #{ast.value} is an invalid Date", [ast]) | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment