Skip to content

Instantly share code, notes, and snippets.

@olange
Last active April 8, 2016 17:55
Show Gist options
  • Save olange/f6c57d3ca577955fc3a51aa62f88c948 to your computer and use it in GitHub Desktop.
Save olange/f6c57d3ca577955fc3a51aa62f88c948 to your computer and use it in GitHub Desktop.
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.
# 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