UniqueEnumValueNamesRule.mjs 1.7 KB

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