HTTP basic updates

This commit is contained in:
julian 2023-09-08 09:18:55 -06:00
parent 02ae941a98
commit 3e9a225470
2 changed files with 29 additions and 11 deletions

View file

@ -7,8 +7,16 @@ import 'package:stackwallet/utilities/logger.dart';
// WIP wrapper layer
abstract class HTTP {
static Future<HttpClientResponse> get({
// TODO expand this class
class Response {
final int code;
final String body;
Response(this.body, this.code);
}
class HTTP {
Future<Response> get({
required Uri url,
Map<String, String>? headers,
required bool routeOverTor,
@ -32,7 +40,11 @@ abstract class HTTP {
headers.forEach((key, value) => request.headers.add);
}
return request.close();
final response = await request.close();
return Response(
await response.transform(utf8.decoder).join(),
response.statusCode,
);
} catch (e, s) {
Logging.instance.log(
"HTTP.get() rethrew: $e\n$s",
@ -44,7 +56,7 @@ abstract class HTTP {
}
}
static Future<HttpClientResponse> post({
Future<Response> post({
required Uri url,
Map<String, String>? headers,
Object? body,
@ -73,7 +85,11 @@ abstract class HTTP {
request.write(body);
return request.close();
final response = await request.close();
return Response(
await response.transform(utf8.decoder).join(),
response.statusCode,
);
} catch (e, s) {
Logging.instance.log(
"HTTP.post() rethrew: $e\n$s",

View file

@ -38,6 +38,8 @@ class ChangeNowAPI {
static const String apiVersion = "/v1";
static const String apiVersionV2 = "/v2";
HTTP client = HTTP();
ChangeNowAPI._();
static final ChangeNowAPI _instance = ChangeNowAPI._();
static ChangeNowAPI get instance => _instance;
@ -52,14 +54,14 @@ class ChangeNowAPI {
Future<dynamic> _makeGetRequest(Uri uri) async {
try {
final response = await HTTP.get(
final response = await client.get(
url: uri,
headers: {'Content-Type': 'application/json'},
routeOverTor: Prefs.instance.useTor,
);
String? data;
try {
data = await response.transform(utf8.decoder).join();
data = response.body;
final parsed = jsonDecode(data);
return parsed;
@ -78,7 +80,7 @@ class ChangeNowAPI {
Future<dynamic> _makeGetRequestV2(Uri uri, String apiKey) async {
try {
final response = await HTTP.get(
final response = await client.get(
url: uri,
headers: {
// 'Content-Type': 'application/json',
@ -87,7 +89,7 @@ class ChangeNowAPI {
routeOverTor: Prefs.instance.useTor,
);
final data = await response.transform(utf8.decoder).join();
final data = response.body;
final parsed = jsonDecode(data);
return parsed;
@ -103,7 +105,7 @@ class ChangeNowAPI {
Map<String, String> body,
) async {
try {
final response = await HTTP.post(
final response = await client.post(
url: uri,
headers: {'Content-Type': 'application/json'},
body: jsonEncode(body),
@ -112,7 +114,7 @@ class ChangeNowAPI {
String? data;
try {
data = await response.transform(utf8.decoder).join();
data = response.body;
final parsed = jsonDecode(data);
return parsed;