UNPKG

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