Skip to content

Commit 3bd0d95

Browse files
authored
add request queuing while refreshing token (#424)
1 parent 5a56f15 commit 3bd0d95

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

examples/gql_example_http_auth_link/lib/http_auth_link.dart

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import "dart:async";
2+
13
import "package:gql_error_link/gql_error_link.dart";
24
import "package:gql_exec/gql_exec.dart";
35
import "package:gql_http_link/gql_http_link.dart";
@@ -8,6 +10,9 @@ class HttpAuthLink extends Link {
810
late Link _link;
911
String? _token;
1012

13+
bool _isRefreshing = false;
14+
final List<Completer> _tokenRefreshQueue = [];
15+
1116
HttpAuthLink() {
1217
_link = Link.concat(
1318
ErrorLink(onException: handleException),
@@ -16,10 +21,25 @@ class HttpAuthLink extends Link {
1621
}
1722

1823
Future<void> updateToken() async {
19-
_token = await Future.delayed(
20-
Duration(milliseconds: 10),
21-
() => "Valid token",
22-
);
24+
if (!_isRefreshing) {
25+
_isRefreshing = true;
26+
27+
_token = await Future.delayed(
28+
Duration(milliseconds: 10),
29+
() => "Valid token",
30+
);
31+
32+
_isRefreshing = false;
33+
_tokenRefreshQueue.forEach((completer) {
34+
completer.complete(_token!);
35+
});
36+
_tokenRefreshQueue.clear();
37+
} else {
38+
// If token refresh is already in progress, queue the request
39+
final completer = Completer<String>();
40+
_tokenRefreshQueue.add(completer);
41+
_token = await completer.future;
42+
}
2343
}
2444

2545
Stream<Response> handleException(

0 commit comments

Comments
 (0)