send<BodyType, InnerType> method

Future<Response<BodyType>> send<BodyType, InnerType>(
  1. Request request, {
  2. ConvertRequest? requestConverter,
  3. ConvertResponse? responseConverter,
})

Sends a pre-build Request, applying all provided Interceptors and Converters.

BodyType should be the expected type of the response body (e.g., String or CustomObject).

If BodyType is a List or a BuiltList, InnerType should be type of the generic parameter (e.g., convertResponse<List<CustomObject>, CustomObject>(response)).

Response<List<CustomObject>> res = await send<List<CustomObject>, CustomObject>(request);

Implementation

Future<Response<BodyType>> send<BodyType, InnerType>(
  Request request, {
  ConvertRequest? requestConverter,
  ConvertResponse? responseConverter,
}) async {
  final Request req = await _interceptRequest(
    await _handleRequestConverter(request, requestConverter),
  );

  _requestController.add(req);

  final streamRes = await httpClient.send(await req.toBaseRequest());
  if (isTypeOf<BodyType, Stream<List<int>>>()) {
    return Response(streamRes, (streamRes.stream) as BodyType);
  }

  final response = await http.Response.fromStream(streamRes);
  dynamic res = Response(response, response.body);

  if (authenticator != null) {
    final Request? updatedRequest =
        await authenticator!.authenticate(req, res, request);

    if (updatedRequest != null) {
      res = await send<BodyType, InnerType>(
        updatedRequest,
        requestConverter: requestConverter,
        responseConverter: responseConverter,
      );
      // To prevent double call with typed response
      if (_responseIsSuccessful(res.statusCode)) {
        await authenticator!.onAuthenticationSuccessful
            ?.call(updatedRequest, res, request);
        return _processResponse(res);
      } else {
        res = await _handleErrorResponse<BodyType, InnerType>(res);
        await authenticator!.onAuthenticationFailed
            ?.call(updatedRequest, res, request);
        return _processResponse(res);
      }
    }
  }

  res = _responseIsSuccessful(res.statusCode)
      ? await _handleSuccessResponse<BodyType, InnerType>(
          res,
          responseConverter,
        )
      : await _handleErrorResponse<BodyType, InnerType>(res);

  return _processResponse(res);
}