UniqueFieldDefinitionNames.js 2.6 KB

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