Created
April 29, 2019 22:29
-
-
Save seansullivan/c6691d3001e6fc08414ef143d425f0b0 to your computer and use it in GitHub Desktop.
GraphQL UUIDv4 Custom Scalar Type
This file contains hidden or 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
const validator = require('validator'); | |
const UUIDv4Error = 'Invalid UUIDv4'; | |
const validateUUIDv4 = value => validator.isUUID(value, 4); | |
exports.UUIDv4 = new GraphQLScalarType({ | |
name: 'UUIDv4', | |
description: 'Valid UUIDv4', | |
serialize(value) { // result coercion | |
if (validateUUIDv4(value)) { | |
return value; | |
} | |
throw new Error(UUIDv4Error); | |
}, | |
parseValue(value) { // input coercion | |
if (validateUUIDv4(value)) { | |
return value; | |
} | |
throw new Error(UUIDv4Error); | |
}, | |
parseLiteral(ast) { // input coercion | |
if (validateUUIDv4(ast.value)) { | |
return ast.value; | |
} | |
throw new Error(UUIDv4Error); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment