UniqueFieldDefinitionNamesRule.mjs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { GraphQLError } from "../../error/GraphQLError.mjs";
  2. import { isObjectType, isInterfaceType, isInputObjectType } from "../../type/definition.mjs";
  3. /**
  4. * Unique field definition names
  5. *
  6. * A GraphQL complex type is only valid if all its fields are uniquely named.
  7. */
  8. export function UniqueFieldDefinitionNamesRule(context) {
  9. var schema = context.getSchema();
  10. var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);
  11. var knownFieldNames = Object.create(null);
  12. return {
  13. InputObjectTypeDefinition: checkFieldUniqueness,
  14. InputObjectTypeExtension: checkFieldUniqueness,
  15. InterfaceTypeDefinition: checkFieldUniqueness,
  16. InterfaceTypeExtension: checkFieldUniqueness,
  17. ObjectTypeDefinition: checkFieldUniqueness,
  18. ObjectTypeExtension: checkFieldUniqueness
  19. };
  20. function checkFieldUniqueness(node) {
  21. var _node$fields;
  22. var typeName = node.name.value;
  23. if (!knownFieldNames[typeName]) {
  24. knownFieldNames[typeName] = Object.create(null);
  25. } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')
  26. var fieldNodes = (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : [];
  27. var fieldNames = knownFieldNames[typeName];
  28. for (var _i2 = 0; _i2 < fieldNodes.length; _i2++) {
  29. var fieldDef = fieldNodes[_i2];
  30. var fieldName = fieldDef.name.value;
  31. if (hasField(existingTypeMap[typeName], fieldName)) {
  32. context.reportError(new GraphQLError("Field \"".concat(typeName, ".").concat(fieldName, "\" already exists in the schema. It cannot also be defined in this type extension."), fieldDef.name));
  33. } else if (fieldNames[fieldName]) {
  34. context.reportError(new GraphQLError("Field \"".concat(typeName, ".").concat(fieldName, "\" can only be defined once."), [fieldNames[fieldName], fieldDef.name]));
  35. } else {
  36. fieldNames[fieldName] = fieldDef.name;
  37. }
  38. }
  39. return false;
  40. }
  41. }
  42. function hasField(type, fieldName) {
  43. if (isObjectType(type) || isInterfaceType(type) || isInputObjectType(type)) {
  44. return type.getFields()[fieldName] != null;
  45. }
  46. return false;
  47. }