fetch method

  1. @override
Future<ResponseBody> fetch(
  1. RequestOptions options,
  2. Stream<Uint8List>? requestStream,
  3. Future<void>? cancelFuture
)

Implement this method to make real HTTP requests.

options are the request options.

requestStream is the request stream. It will not be null only when the request body is not empty. Use requestStream if your code rely on RequestOptions.onSendProgress.

cancelFuture corresponds to CancelToken handling. When the request is canceled, cancelFuture will be resolved. To await if a request has been canceled:

cancelFuture?.then((_) => print('request cancelled!'));

Implementation

@override
Future<ResponseBody> fetch(
  RequestOptions options,
  Stream<Uint8List>? requestStream,
  Future<void>? cancelFuture,
) async {
  final request = RecordedRequest(
    method: options.method.toUpperCase(),
    uri: options.uri,
    headers: Map<String, dynamic>.of(options.headers),
    body: options.data,
  );
  _requests.add(request);

  final route = _routes
      .where(
        (r) =>
            r.method == request.method && _matchesPath(r.path, request.path),
      )
      .firstOrNull;

  if (route == null) {
    if (strict) {
      throw StateError('No mock route for $request');
    }

    return _toBody(
      MockResponse.wpError(
        statusCode: 404,
        code: 'rest_no_route',
        message: 'No route was found matching the URL and request method.',
      ),
    );
  }

  final response = await route.handler(request);

  if (response.delay > Duration.zero) {
    await Future<void>.delayed(response.delay);
  }

  final error = response.error;
  if (error != null) {
    throw DioException(
      requestOptions: options,
      type: response.errorType,
      message: error,
    );
  }

  return _toBody(response);
}