request<TBodyType, TResponseType> method

Future<TResponseType> request<TBodyType, TResponseType>(
  1. String url,
  2. TBodyType body,
  3. TResponseType fromJson(
    1. Map<String, dynamic>
    )
)

Implementation

Future<TResponseType> request<TBodyType, TResponseType>(
  String url,
  TBodyType body,
  TResponseType Function(Map<String, dynamic>) fromJson,
) async {
  final fullUrl = '${config.baseUrl}$url';
  final stringifiedBody = jsonEncode(body);
  final stamp = await stamper.stamp(stringifiedBody);

  final client = HttpClient();
  try {
    final request = await client.postUrl(Uri.parse(fullUrl));
    request.headers.set(stamp.stampHeaderName, stamp.stampHeaderValue);
    request.headers.set('X-Client-Version', VERSION);
    request.headers.contentType = ContentType.json;
    request.write(stringifiedBody);

    final response = await request.close();

    if (response.statusCode != 200) {
      final errorBody = await response.transform(utf8.decoder).join();
      throw TurnkeyRequestError(
        GrpcStatus.fromJson(jsonDecode(errorBody)),
      );
    }

    final responseBody = await response.transform(utf8.decoder).join();
    final decodedJson = jsonDecode(responseBody) as Map<String, dynamic>;

    return fromJson(decodedJson);
  } finally {
    client.close();
  }
}