doJSONRequest function

Future<String> doJSONRequest(
  1. Context ctx,
  2. Uri url,
  3. ClientHooks hooks,
  4. GeneratedMessage msgReq,
)

Implementation

Future<String> doJSONRequest(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/json');

    // add request data to body
    req.body = json.encode(msgReq.toProto3Json());

    // 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) {
      final data = await res.stream.transform(utf8.decoder).join().then((data) {
        hooks.onResponseReceived(ctx);
        return data;
      });
      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();
  }
}