mirror of
https://github.com/foss42/apidash.git
synced 2025-08-26 06:11:06 +08:00
feat: add ability to cancel in-flight HTTP requests and manage client lifecycle
This commit is contained in:
33
packages/apidash_core/lib/services/client_manager.dart
Normal file
33
packages/apidash_core/lib/services/client_manager.dart
Normal file
@ -0,0 +1,33 @@
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
class HttpClientManager {
|
||||
static final HttpClientManager _instance = HttpClientManager._internal();
|
||||
final Map<String, http.Client> _clients = {};
|
||||
|
||||
factory HttpClientManager() {
|
||||
return _instance;
|
||||
}
|
||||
|
||||
HttpClientManager._internal();
|
||||
|
||||
http.Client createClient(String requestId) {
|
||||
final client = http.Client();
|
||||
_clients[requestId] = client;
|
||||
return client;
|
||||
}
|
||||
|
||||
void cancelRequest(String requestId) {
|
||||
if (_clients.containsKey(requestId)) {
|
||||
_clients[requestId]?.close();
|
||||
_clients.remove(requestId);
|
||||
}
|
||||
}
|
||||
|
||||
void closeClient(String requestId) {
|
||||
cancelRequest(requestId);
|
||||
}
|
||||
|
||||
bool hasActiveClient(String requestId) {
|
||||
return _clients.containsKey(requestId);
|
||||
}
|
||||
}
|
@ -6,14 +6,22 @@ import 'package:seed/seed.dart';
|
||||
import '../consts.dart';
|
||||
import '../models/models.dart';
|
||||
import '../utils/utils.dart';
|
||||
import 'client_manager.dart';
|
||||
|
||||
typedef HttpResponse = http.Response;
|
||||
|
||||
Future<(HttpResponse?, Duration?, String?)> request(
|
||||
HttpRequestModel requestModel, {
|
||||
String defaultUriScheme = kDefaultUriScheme,
|
||||
http.Client? client,
|
||||
String? requestId,
|
||||
}) async {
|
||||
final clientManager = HttpClientManager();
|
||||
http.Client? client;
|
||||
|
||||
if (requestId != null) {
|
||||
client = clientManager.createClient(requestId);
|
||||
}
|
||||
|
||||
(Uri?, String?) uriRec = getValidRequestUri(
|
||||
requestModel.url,
|
||||
requestModel.enabledParams,
|
||||
@ -110,6 +118,9 @@ Future<(HttpResponse?, Duration?, String?)> request(
|
||||
if (shouldCloseClient) {
|
||||
client?.close();
|
||||
}
|
||||
if (requestId != null) {
|
||||
clientManager.closeClient(requestId);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return (null, null, uriRec.$2);
|
||||
|
@ -1 +1,2 @@
|
||||
export 'http_service.dart';
|
||||
export 'client_manager.dart';
|
||||
|
Reference in New Issue
Block a user