UniqueFieldDefinitionNamesRule.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true,
  4. });
  5. exports.UniqueFieldDefinitionNamesRule = UniqueFieldDefinitionNamesRule;
  6. var _GraphQLError = require('../../error/GraphQLError.js');
  7. var _definition = require('../../type/definition.js');
  8. /**
  9. * Unique field definition names
  10. *
  11. * A GraphQL complex type is only valid if all its fields are uniquely named.
  12. */
  13. function UniqueFieldDefinitionNamesRule(context) {
  14. const schema = context.getSchema();
  15. const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);
  16. const knownFieldNames = Object.create(null);
  17. return {
  18. InputObjectTypeDefinition: checkFieldUniqueness,
  19. InputObjectTypeExtension: checkFieldUniqueness,
  20. InterfaceTypeDefinition: checkFieldUniqueness,
  21. InterfaceTypeExtension: checkFieldUniqueness,
  22. ObjectTypeDefinition: checkFieldUniqueness,
  23. ObjectTypeExtension: checkFieldUniqueness,
  24. };
  25. function checkFieldUniqueness(node) {
  26. var _node$fields;
  27. const typeName = node.name.value;
  28. if (!knownFieldNames[typeName]) {
  29. knownFieldNames[typeName] = Object.create(null);
  30. } // FIXME: https://github.com/graphql/graphql-js/issues/2203
  31. /* c8 ignore next */
  32. const fieldNodes =
  33. (_node$fields = node.fields) !== null && _node$fields !== void 0
  34. ? _node$fields
  35. : [];
  36. const fieldNames = knownFieldNames[typeName];
  37. for (const fieldDef of fieldNodes) {
  38. const fieldName = fieldDef.name.value;
  39. if (hasField(existingTypeMap[typeName], fieldName)) {
  40. context.reportError(
  41. new _GraphQLError.GraphQLError(
  42. `Field "${typeName}.${fieldName}" already exists in the schema. It cannot also be defined in this type extension.`,
  43. {
  44. nodes: fieldDef.name,
  45. },
  46. ),
  47. );
  48. } else if (fieldNames[fieldName]) {
  49. context.reportError(
  50. new _GraphQLError.GraphQLError(
  51. `Field "${typeName}.${fieldName}" can only be defined once.`,
  52. {
  53. nodes: [fieldNames[fieldName], fieldDef.name],
  54. },
  55. ),
  56. );
  57. } else {
  58. fieldNames[fieldName] = fieldDef.name;
  59. }
  60. }
  61. return false;
  62. }
  63. }
  64. function hasField(type, fieldName) {
  65. if (
  66. (0, _definition.isObjectType)(type) ||
  67. (0, _definition.isInterfaceType)(type) ||
  68. (0, _definition.isInputObjectType)(type)
  69. ) {
  70. return type.getFields()[fieldName] != null;
  71. }
  72. return false;
  73. }