uuid.mjs 982 B

123456789101112131415161718192021222324252627282930313233343536
  1. import { Kind, GraphQLScalarType } from 'graphql'
  2. 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
  3. const nilUUID = '00000000-0000-0000-0000-000000000000'
  4. function isUUID (value) {
  5. return uuidRegex.test(value) || nilUUID === value
  6. }
  7. export default new GraphQLScalarType({
  8. name: 'UUID',
  9. description: 'The `UUID` scalar type represents UUID values as specified by [RFC 4122](https://datatracker.ietf.org/doc/html/rfc4122).',
  10. serialize: (value) => {
  11. if (!isUUID(value)) {
  12. throw new TypeError(`UUID cannot represent non-UUID value: ${value}`)
  13. }
  14. return value.toLowerCase()
  15. },
  16. parseValue: (value) => {
  17. if (!isUUID(value)) {
  18. throw new TypeError(`UUID cannot represent non-UUID value: ${value}`)
  19. }
  20. return value.toLowerCase()
  21. },
  22. parseLiteral: (ast) => {
  23. if (ast.kind === Kind.STRING) {
  24. if (isUUID(ast.value)) {
  25. return ast.value
  26. }
  27. }
  28. return undefined
  29. }
  30. })