dynamicRequest<T> method
Sends a dynamic HTTP request.
method is the HTTP method (GET, POST, PUT, etc.).
url is the endpoint URL.
body is the body of the request (for POST, PUT, etc.).
addHeaders are additional headers for the request.
Implementation
Future<Either<T?, int>> dynamicRequest<T>({
required String method,
required String url,
dynamic body,
Map<String, String>? addHeaders,
}) async {
final HttpClient httpClient = HttpClient();
try {
final Uri urlParse = Uri.parse(url);
if (body != null && method == HTTPAdapter.methodGet) {
urlParse.replace(queryParameters: body as Map<String, dynamic>);
}
try {
final HttpClientRequest request = await httpClient.getUrl(urlParse);
if (addHeaders != null) {
addHeaders.forEach((key, value) {
request.headers.add(key, value);
});
}
if (body != null && method != HTTPAdapter.methodGet) {
request.write(jsonEncode(body));
}
final HttpClientResponse response = await request.close();
return getResponse<T>(response);
} catch (e) {
if (e is SocketException) {
return Right<T?, int>(e.osError?.errorCode ?? -1);
}
return Right<T?, int>(-1);
}
} finally {
httpClient.close();
}
}