UniqueEnumValueNamesRule.mjs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. const schema = context.getSchema();
  10. const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);
  11. const knownValueNames = Object.create(null);
  12. return {
  13. EnumTypeDefinition: checkValueUniqueness,
  14. EnumTypeExtension: checkValueUniqueness,
  15. };
  16. function checkValueUniqueness(node) {
  17. var _node$values;
  18. const typeName = node.name.value;
  19. if (!knownValueNames[typeName]) {
  20. knownValueNames[typeName] = Object.create(null);
  21. } // FIXME: https://github.com/graphql/graphql-js/issues/2203
  22. /* c8 ignore next */
  23. const valueNodes =
  24. (_node$values = node.values) !== null && _node$values !== void 0
  25. ? _node$values
  26. : [];
  27. const valueNames = knownValueNames[typeName];
  28. for (const valueDef of valueNodes) {
  29. const valueName = valueDef.name.value;
  30. const existingType = existingTypeMap[typeName];
  31. if (isEnumType(existingType) && existingType.getValue(valueName)) {
  32. context.reportError(
  33. new GraphQLError(
  34. `Enum value "${typeName}.${valueName}" already exists in the schema. It cannot also be defined in this type extension.`,
  35. {
  36. nodes: valueDef.name,
  37. },
  38. ),
  39. );
  40. } else if (valueNames[valueName]) {
  41. context.reportError(
  42. new GraphQLError(
  43. `Enum value "${typeName}.${valueName}" can only be defined once.`,
  44. {
  45. nodes: [valueNames[valueName], valueDef.name],
  46. },
  47. ),
  48. );
  49. } else {
  50. valueNames[valueName] = valueDef.name;
  51. }
  52. }
  53. return false;
  54. }
  55. }