validateDocument function

List<GraphQLError> validateDocument(
  1. GraphQLSchema schema,
  2. DocumentNode document, {
  3. int maxErrors = 100,
  4. List<ValidationRule> rules = specifiedRules,
})

Executes the default GraphQL validations for the given document over the schema.

maxErrors is the maximum number of errors returned in the validation.

Implementation

List<GraphQLError> validateDocument(
  GraphQLSchema schema,
  DocumentNode document, {
  int maxErrors = 100,
  List<ValidationRule> rules = specifiedRules,
}) {
  // assertValidSchema(schema);

  final _errors = <GraphQLError>[];
  final typeInfo = TypeInfo(schema);
  late final WithTypeInfoVisitor visitor;
  final ctx = ValidationCtx(
    schema,
    document,
    typeInfo,
    onError: (error) {
      if (_errors.length >= maxErrors) {
        _errors.add(
          GraphQLError(
            'Too many validation errors, error limit reached.'
            ' Validation aborted.',
          ),
        );
        throw _AbortValidationException();
      }
      if (error.locations.isEmpty) {
        _errors.add(GraphQLError(
          error.message,
          extensions: error.extensions,
          path: error.path,
          sourceError: error.sourceError,
          stackTrace: error.stackTrace,
          locations: GraphQLErrorLocation.firstFromNodes(
            visitor.ancestors.reversed,
          ),
        ));
      } else {
        _errors.add(error);
      }
    },
  );

  visitor = WithTypeInfoVisitor(
    typeInfo,
    visitors: rules.map((e) => e(ctx)).toList(),
    onAccept: (result) {
      if (result is List<GraphQLError>) {
        // TODO: 3I these are returning error when visiting, not by using reportError
        result.forEach(ctx.reportError);
      }
    },
  );

  try {
    document.accept(visitor);
  } on _AbortValidationException catch (_) {}

  return _errors;
}