UNPKG

2.26 kBJavaScriptView Raw
1import didYouMean from "../../jsutils/didYouMean.mjs";
2import suggestionList from "../../jsutils/suggestionList.mjs";
3import { GraphQLError } from "../../error/GraphQLError.mjs";
4import { isTypeDefinitionNode, isTypeSystemDefinitionNode, isTypeSystemExtensionNode } from "../../language/predicates.mjs";
5import { specifiedScalarTypes } from "../../type/scalars.mjs";
6import { introspectionTypes } from "../../type/introspection.mjs";
7
8/**
9 * Known type names
10 *
11 * A GraphQL document is only valid if referenced types (specifically
12 * variable definitions and fragment conditions) are defined by the type schema.
13 */
14export function KnownTypeNamesRule(context) {
15 var schema = context.getSchema();
16 var existingTypesMap = schema ? schema.getTypeMap() : Object.create(null);
17 var definedTypes = Object.create(null);
18
19 for (var _i2 = 0, _context$getDocument$2 = context.getDocument().definitions; _i2 < _context$getDocument$2.length; _i2++) {
20 var def = _context$getDocument$2[_i2];
21
22 if (isTypeDefinitionNode(def)) {
23 definedTypes[def.name.value] = true;
24 }
25 }
26
27 var typeNames = Object.keys(existingTypesMap).concat(Object.keys(definedTypes));
28 return {
29 NamedType: function NamedType(node, _1, parent, _2, ancestors) {
30 var typeName = node.name.value;
31
32 if (!existingTypesMap[typeName] && !definedTypes[typeName]) {
33 var _ancestors$;
34
35 var definitionNode = (_ancestors$ = ancestors[2]) !== null && _ancestors$ !== void 0 ? _ancestors$ : parent;
36 var isSDL = definitionNode != null && isSDLNode(definitionNode);
37
38 if (isSDL && isStandardTypeName(typeName)) {
39 return;
40 }
41
42 var suggestedTypes = suggestionList(typeName, isSDL ? standardTypeNames.concat(typeNames) : typeNames);
43 context.reportError(new GraphQLError("Unknown type \"".concat(typeName, "\".") + didYouMean(suggestedTypes), node));
44 }
45 }
46 };
47}
48var standardTypeNames = [].concat(specifiedScalarTypes, introspectionTypes).map(function (type) {
49 return type.name;
50});
51
52function isStandardTypeName(typeName) {
53 return standardTypeNames.indexOf(typeName) !== -1;
54}
55
56function isSDLNode(value) {
57 return !Array.isArray(value) && (isTypeSystemDefinitionNode(value) || isTypeSystemExtensionNode(value));
58}