Skip to content

Instantly share code, notes, and snippets.

@seansullivan
Created April 29, 2019 22:29
Show Gist options
  • Save seansullivan/c6691d3001e6fc08414ef143d425f0b0 to your computer and use it in GitHub Desktop.
Save seansullivan/c6691d3001e6fc08414ef143d425f0b0 to your computer and use it in GitHub Desktop.
GraphQL UUIDv4 Custom Scalar Type
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