UniqueEnumValueNamesRule.js 1.9 KB

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