UniqueEnumValueNamesRule.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true,
  4. });
  5. exports.UniqueEnumValueNamesRule = UniqueEnumValueNamesRule;
  6. var _GraphQLError = require('../../error/GraphQLError.js');
  7. var _definition = require('../../type/definition.js');
  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. const schema = context.getSchema();
  15. const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);
  16. const knownValueNames = Object.create(null);
  17. return {
  18. EnumTypeDefinition: checkValueUniqueness,
  19. EnumTypeExtension: checkValueUniqueness,
  20. };
  21. function checkValueUniqueness(node) {
  22. var _node$values;
  23. const typeName = node.name.value;
  24. if (!knownValueNames[typeName]) {
  25. knownValueNames[typeName] = Object.create(null);
  26. } // FIXME: https://github.com/graphql/graphql-js/issues/2203
  27. /* c8 ignore next */
  28. const valueNodes =
  29. (_node$values = node.values) !== null && _node$values !== void 0
  30. ? _node$values
  31. : [];
  32. const valueNames = knownValueNames[typeName];
  33. for (const valueDef of valueNodes) {
  34. const valueName = valueDef.name.value;
  35. const existingType = existingTypeMap[typeName];
  36. if (
  37. (0, _definition.isEnumType)(existingType) &&
  38. existingType.getValue(valueName)
  39. ) {
  40. context.reportError(
  41. new _GraphQLError.GraphQLError(
  42. `Enum value "${typeName}.${valueName}" already exists in the schema. It cannot also be defined in this type extension.`,
  43. {
  44. nodes: valueDef.name,
  45. },
  46. ),
  47. );
  48. } else if (valueNames[valueName]) {
  49. context.reportError(
  50. new _GraphQLError.GraphQLError(
  51. `Enum value "${typeName}.${valueName}" can only be defined once.`,
  52. {
  53. nodes: [valueNames[valueName], valueDef.name],
  54. },
  55. ),
  56. );
  57. } else {
  58. valueNames[valueName] = valueDef.name;
  59. }
  60. }
  61. return false;
  62. }
  63. }