UNPKG

1.65 kBJavaScriptView Raw
1import { GraphQLError } from "../../error/GraphQLError.mjs";
2
3/**
4 * Unique operation types
5 *
6 * A GraphQL document is only valid if it has only one type per operation.
7 */
8export function UniqueOperationTypesRule(context) {
9 var schema = context.getSchema();
10 var definedOperationTypes = Object.create(null);
11 var existingOperationTypes = schema ? {
12 query: schema.getQueryType(),
13 mutation: schema.getMutationType(),
14 subscription: schema.getSubscriptionType()
15 } : {};
16 return {
17 SchemaDefinition: checkOperationTypes,
18 SchemaExtension: checkOperationTypes
19 };
20
21 function checkOperationTypes(node) {
22 var _node$operationTypes;
23
24 // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')
25 var operationTypesNodes = (_node$operationTypes = node.operationTypes) !== null && _node$operationTypes !== void 0 ? _node$operationTypes : [];
26
27 for (var _i2 = 0; _i2 < operationTypesNodes.length; _i2++) {
28 var operationType = operationTypesNodes[_i2];
29 var operation = operationType.operation;
30 var alreadyDefinedOperationType = definedOperationTypes[operation];
31
32 if (existingOperationTypes[operation]) {
33 context.reportError(new GraphQLError("Type for ".concat(operation, " already defined in the schema. It cannot be redefined."), operationType));
34 } else if (alreadyDefinedOperationType) {
35 context.reportError(new GraphQLError("There can be only one ".concat(operation, " type in schema."), [alreadyDefinedOperationType, operationType]));
36 } else {
37 definedOperationTypes[operation] = operationType;
38 }
39 }
40
41 return false;
42 }
43}