run<T> method
Run a given query
Implementation
Future<T> run<T>(LemmyApiQuery<T> query) async {
// get a future based on http method
final res = await () {
switch (query.httpMethod) {
case HttpMethod.get:
return http.get(
Uri.https(
host,
'$extraPath${query.path}',
<String, String>{
for (final entry in query.toJson().entries)
entry.key: entry.value.toString()
},
),
);
case HttpMethod.post:
return http.post(
Uri.https(host, '$extraPath${query.path}'),
body: jsonEncode(query.toJson()),
headers: const {'Content-Type': 'application/json'},
);
case HttpMethod.put:
return http.put(
Uri.https(host, '$extraPath${query.path}'),
body: jsonEncode(query.toJson()),
headers: const {'Content-Type': 'application/json'},
);
}
}();
// if status code is not \in [200; 300) then throw an exception with a correct message
if (!res.ok) {
final String errorMessage = () {
try {
final Map<String, dynamic> json = jsonDecode(res.body);
return json['error'];
} on FormatException {
return res.body;
}
}();
throw LemmyApiException(errorMessage);
}
// augment responses with `instance_host`
final Map<String, dynamic> json = jsonDecode(utf8.decode(res.bodyBytes));
_augmentInstanceHost(host, json);
return query.responseFactory(json);
}