Skip to content

Instantly share code, notes, and snippets.

@olange
Created January 30, 2017 14:58
Show Gist options
  • Save olange/5cc116380143acfff5e8896a228b3dcd to your computer and use it in GitHub Desktop.
Save olange/5cc116380143acfff5e8896a228b3dcd to your computer and use it in GitHub Desktop.
A custom GraphQL scalar type that represents an URL (Uniform Resource Locator) and promises to verify that a given URL string has a valid syntax.
exp = module.exports = {}
url = require "url"
type = require "component-type"
graphql = require "graphql"
graphql_language = require "graphql/language"
graphql_error = require "graphql/error"
{ GraphQLScalarType } = graphql
{ GraphQLError } = graphql_error
{ Kind } = graphql_language
# PRIVATE REGION
coerceAsURLObj = (value) ->
if type( value) isnt "string"
throw new GraphQLError( "URL coercion error: can only parse strings to URLs;
got value #{value} of type #{type( value)}")
try
return url.parse( value).href
catch error
throw new GraphQLError( "URL coercion error: value #{value} is an invalid
URL string representation.")
parseURL = (ast) ->
if ast.kind isnt Kind.STRING
throw new GraphQLError( "Query input coercion error: can only parse strings to
URLs; got value #{ast.value} of kind #{ast.kind}", [ast])
coerceAsURLObj ast.value
# PUBLIC REGION
# Defines and exports a custom GraphQL scalar type that represents
# an URL (Uniform Resource Locator) and promises to verify that a
# given URL string is of a valid form.
#
# See also:
# * [Node.js API › URL Module](https://nodejs.org/api/url.html)
# * [WhatWG › URL › URL Syntax specification](https://url.spec.whatwg.org/#syntax-url)
exp.GraphQLURL = new GraphQLScalarType {
name: "URL"
description: "Scalar type that represents an URL, expressed as an URL string."
serialize: coerceAsURLObj # Serialize output value
parseValue: (value) -> # Parse and coerce value from a query variable
parseURL { kind: Kind.STRING, value: value }
parseLiteral: (ast) -> # Parse and coerce a literal value in a query
parseURL ast
}
# eof
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment