UNPKG

1.77 kBJavaScriptView Raw
1import { GraphQLError } from "../../error/GraphQLError.mjs";
2import { isEnumType } from "../../type/definition.mjs";
3
4/**
5 * Unique enum value names
6 *
7 * A GraphQL enum type is only valid if all its values are uniquely named.
8 */
9export function UniqueEnumValueNamesRule(context) {
10 var schema = context.getSchema();
11 var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);
12 var knownValueNames = Object.create(null);
13 return {
14 EnumTypeDefinition: checkValueUniqueness,
15 EnumTypeExtension: checkValueUniqueness
16 };
17
18 function checkValueUniqueness(node) {
19 var _node$values;
20
21 var typeName = node.name.value;
22
23 if (!knownValueNames[typeName]) {
24 knownValueNames[typeName] = Object.create(null);
25 } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')
26
27
28 var valueNodes = (_node$values = node.values) !== null && _node$values !== void 0 ? _node$values : [];
29 var valueNames = knownValueNames[typeName];
30
31 for (var _i2 = 0; _i2 < valueNodes.length; _i2++) {
32 var valueDef = valueNodes[_i2];
33 var valueName = valueDef.name.value;
34 var existingType = existingTypeMap[typeName];
35
36 if (isEnumType(existingType) && existingType.getValue(valueName)) {
37 context.reportError(new GraphQLError("Enum value \"".concat(typeName, ".").concat(valueName, "\" already exists in the schema. It cannot also be defined in this type extension."), valueDef.name));
38 } else if (valueNames[valueName]) {
39 context.reportError(new GraphQLError("Enum value \"".concat(typeName, ".").concat(valueName, "\" can only be defined once."), [valueNames[valueName], valueDef.name]));
40 } else {
41 valueNames[valueName] = valueDef.name;
42 }
43 }
44
45 return false;
46 }
47}