UNPKG

2.62 kBJavaScriptView Raw
1import { GraphQLError } from "../../error/GraphQLError.mjs";
2import { Kind } from "../../language/kinds.mjs";
3import { isTypeDefinitionNode, isTypeExtensionNode } from "../../language/predicates.mjs";
4import { specifiedDirectives } from "../../type/directives.mjs";
5
6/**
7 * Unique directive names per location
8 *
9 * A GraphQL document is only valid if all non-repeatable directives at
10 * a given location are uniquely named.
11 */
12export function UniqueDirectivesPerLocationRule(context) {
13 var uniqueDirectiveMap = Object.create(null);
14 var schema = context.getSchema();
15 var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives;
16
17 for (var _i2 = 0; _i2 < definedDirectives.length; _i2++) {
18 var directive = definedDirectives[_i2];
19 uniqueDirectiveMap[directive.name] = !directive.isRepeatable;
20 }
21
22 var astDefinitions = context.getDocument().definitions;
23
24 for (var _i4 = 0; _i4 < astDefinitions.length; _i4++) {
25 var def = astDefinitions[_i4];
26
27 if (def.kind === Kind.DIRECTIVE_DEFINITION) {
28 uniqueDirectiveMap[def.name.value] = !def.repeatable;
29 }
30 }
31
32 var schemaDirectives = Object.create(null);
33 var typeDirectivesMap = Object.create(null);
34 return {
35 // Many different AST nodes may contain directives. Rather than listing
36 // them all, just listen for entering any node, and check to see if it
37 // defines any directives.
38 enter: function enter(node) {
39 if (node.directives == null) {
40 return;
41 }
42
43 var seenDirectives;
44
45 if (node.kind === Kind.SCHEMA_DEFINITION || node.kind === Kind.SCHEMA_EXTENSION) {
46 seenDirectives = schemaDirectives;
47 } else if (isTypeDefinitionNode(node) || isTypeExtensionNode(node)) {
48 var typeName = node.name.value;
49 seenDirectives = typeDirectivesMap[typeName];
50
51 if (seenDirectives === undefined) {
52 typeDirectivesMap[typeName] = seenDirectives = Object.create(null);
53 }
54 } else {
55 seenDirectives = Object.create(null);
56 }
57
58 for (var _i6 = 0, _node$directives2 = node.directives; _i6 < _node$directives2.length; _i6++) {
59 var _directive = _node$directives2[_i6];
60 var directiveName = _directive.name.value;
61
62 if (uniqueDirectiveMap[directiveName]) {
63 if (seenDirectives[directiveName]) {
64 context.reportError(new GraphQLError("The directive \"@".concat(directiveName, "\" can only be used once at this location."), [seenDirectives[directiveName], _directive]));
65 } else {
66 seenDirectives[directiveName] = _directive;
67 }
68 }
69 }
70 }
71 };
72}