uuid.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. const { Kind, GraphQLScalarType } = require('graphql')
  2. // const { Kind } = require('graphql/language')
  3. const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
  4. const nilUUID = '00000000-0000-0000-0000-000000000000'
  5. function isUUID (value) {
  6. return uuidRegex.test(value) || nilUUID === value
  7. }
  8. module.exports = {
  9. UUID: new GraphQLScalarType({
  10. name: 'UUID',
  11. description: 'The `UUID` scalar type represents UUID values as specified by [RFC 4122](https://tools.ietf.org/html/rfc4122).',
  12. serialize: (value) => {
  13. if (!isUUID(value)) {
  14. throw new TypeError(`UUID cannot represent non-UUID value: ${value}`)
  15. }
  16. return value.toLowerCase()
  17. },
  18. parseValue: (value) => {
  19. if (!isUUID(value)) {
  20. throw new TypeError(`UUID cannot represent non-UUID value: ${value}`)
  21. }
  22. return value.toLowerCase()
  23. },
  24. parseLiteral: (ast) => {
  25. if (ast.kind === Kind.STRING) {
  26. if (isUUID(ast.value)) {
  27. return ast.value
  28. }
  29. }
  30. return undefined
  31. }
  32. })
  33. }