UniqueEnumValueNames.mjs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { GraphQLError } from '../../error/GraphQLError';
  2. import { isEnumType } from '../../type/definition';
  3. export function duplicateEnumValueNameMessage(typeName, valueName) {
  4. return "Enum value \"".concat(typeName, ".").concat(valueName, "\" can only be defined once.");
  5. }
  6. export function existedEnumValueNameMessage(typeName, valueName) {
  7. return "Enum value \"".concat(typeName, ".").concat(valueName, "\" already exists in the schema. It cannot also be defined in this type extension.");
  8. }
  9. /**
  10. * Unique enum value names
  11. *
  12. * A GraphQL enum type is only valid if all its values are uniquely named.
  13. */
  14. export function UniqueEnumValueNames(context) {
  15. var schema = context.getSchema();
  16. var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);
  17. var knownValueNames = Object.create(null);
  18. return {
  19. EnumTypeDefinition: checkValueUniqueness,
  20. EnumTypeExtension: checkValueUniqueness
  21. };
  22. function checkValueUniqueness(node) {
  23. var typeName = node.name.value;
  24. if (!knownValueNames[typeName]) {
  25. knownValueNames[typeName] = Object.create(null);
  26. }
  27. if (node.values) {
  28. var valueNames = knownValueNames[typeName];
  29. for (var _i2 = 0, _node$values2 = node.values; _i2 < _node$values2.length; _i2++) {
  30. var valueDef = _node$values2[_i2];
  31. var valueName = valueDef.name.value;
  32. var existingType = existingTypeMap[typeName];
  33. if (isEnumType(existingType) && existingType.getValue(valueName)) {
  34. context.reportError(new GraphQLError(existedEnumValueNameMessage(typeName, valueName), valueDef.name));
  35. } else if (valueNames[valueName]) {
  36. context.reportError(new GraphQLError(duplicateEnumValueNameMessage(typeName, valueName), [valueNames[valueName], valueDef.name]));
  37. } else {
  38. valueNames[valueName] = valueDef.name;
  39. }
  40. }
  41. }
  42. return false;
  43. }
  44. }