doProtobufRequest function

Future<List<int>> doProtobufRequest(
  1. Context ctx,
  2. Uri url,
  3. ClientHooks hooks,
  4. GeneratedMessage msgReq,
)

Implementation

Future<List<int>> doProtobufRequest(twirp.Context ctx, Uri url,
    twirp.ClientHooks hooks, GeneratedMessage msgReq) async {
  // setup http client
  final httpClient = http.Client();

  try {
    // create http request
    final req = createRequest(url, ctx, 'application/protobuf');

    // add request data to body
    req.bodyBytes = msgReq.writeToBuffer();

    // call onRequestPrepared hook for user to modify request
    ctx = await hooks.onRequestPrepared(ctx, req);

    // send data
    final res = await httpClient.send(req);

    // if success, parse and return response
    if (res.statusCode == 200) {
      List<int> data = <int>[];
      await res.stream.listen((value) {
        data.addAll(value);
      }).asFuture();
      hooks.onResponseReceived(ctx);
      return Future.value(data);
    }

    // we received a twirp related error
    throw twirp.TwirpError.fromJson(
        json.decode(await res.stream.transform(utf8.decoder).join()), ctx);
  } on twirp.TwirpError catch (twirpErr) {
    hooks.onError(ctx, twirpErr);
    rethrow;
  } catch (e) {
    // catch http connection error or from onRequestPrepared
    final twirpErr = twirp.TwirpError.fromConnectionError(e.toString(), ctx);
    hooks.onError(ctx, twirpErr);
    throw twirpErr;
  } finally {
    httpClient.close();
  }
}