UniqueFieldDefinitionNamesRule.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. var schema = context.getSchema();
  15. var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);
  16. var 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. var typeName = node.name.value;
  28. if (!knownFieldNames[typeName]) {
  29. knownFieldNames[typeName] = Object.create(null);
  30. } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')
  31. var fieldNodes = (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : [];
  32. var fieldNames = knownFieldNames[typeName];
  33. for (var _i2 = 0; _i2 < fieldNodes.length; _i2++) {
  34. var fieldDef = fieldNodes[_i2];
  35. var fieldName = fieldDef.name.value;
  36. if (hasField(existingTypeMap[typeName], fieldName)) {
  37. context.reportError(new _GraphQLError.GraphQLError("Field \"".concat(typeName, ".").concat(fieldName, "\" already exists in the schema. It cannot also be defined in this type extension."), fieldDef.name));
  38. } else if (fieldNames[fieldName]) {
  39. context.reportError(new _GraphQLError.GraphQLError("Field \"".concat(typeName, ".").concat(fieldName, "\" can only be defined once."), [fieldNames[fieldName], fieldDef.name]));
  40. } else {
  41. fieldNames[fieldName] = fieldDef.name;
  42. }
  43. }
  44. return false;
  45. }
  46. }
  47. function hasField(type, fieldName) {
  48. if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type) || (0, _definition.isInputObjectType)(type)) {
  49. return type.getFields()[fieldName] != null;
  50. }
  51. return false;
  52. }