UniqueFieldDefinitionNames.mjs 2.2 KB

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