knownTypeNamesRule function

Visitor knownTypeNamesRule(
  1. SDLValidationCtx ctx
)

Known type names

A GraphQL document is only valid if referenced types (specifically variable definitions and fragment conditions) are defined by the type schema.

See https://spec.graphql.org/draft/#sec-Fragment-Spread-Type-Existence

Implementation

Visitor knownTypeNamesRule(SDLValidationCtx ctx) {
  final typeNames = <String>{};
  final schema = ctx.schema;
  if (schema != null) {
    typeNames.addAll(schema.typeMap.keys);
  }
  for (final def in ctx.document.definitions.whereType<TypeDefinitionNode>()) {
    typeNames.add(def.name.value);
  }

  final visitor = TypedVisitor();

  visitor.add<NamedTypeNode>((NamedTypeNode node) {
    final name = node.name.value;
    if (!typeNames.contains(name)) {
      final ancestors = visitor.ancestors();
      // TODO: 1I check ancestors usage
      final definitionNode =
          ancestors.length > 1 ? ancestors[1] : ancestors[ancestors.length - 1];
      final isSDL = definitionNode is TypeSystemDefinitionNode ||
          definitionNode is TypeSystemExtensionNode;
      if (isSDL &&
          (introspectionTypeNames.contains(name) ||
              specifiedScalarNames.contains(name))) {
        return null;
      }
      ctx.reportError(GraphQLError(
        'Unknown type "$name".',
        locations: GraphQLErrorLocation.listFromSource(node.name.span?.start),
        extensions: _knownTypeNamesSpec.extensions(),
      ));
    }
  });
  return visitor;
}