Skip to content

Commit 2889cb2

Browse files
committed
Enhanced BrowserClient class
1 parent dad889c commit 2889cb2

File tree

1 file changed

+23
-22
lines changed

1 file changed

+23
-22
lines changed

pkgs/http/lib/src/browser_client.dart

Lines changed: 23 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,23 @@ BaseClient createClient() {
2929
return BrowserClient();
3030
}
3131

32+
/// Caching mode used by the [BrowserClient].
33+
///
34+
/// Sets the request cache value of the browser Fetch API.
35+
/// [`Request.cache`](https://developer.mozilla.org/en-US/docs/Web/API/Request/cache) property.
36+
enum CacheMode {
37+
defaultType('default'),
38+
reload('reload'),
39+
noStore('no-store'),
40+
noCache('no-cache'),
41+
forceCache('force-cache'),
42+
onlyIfCached('only-if-cached');
43+
44+
final String cacheType;
45+
46+
const CacheMode(this.cacheType);
47+
}
48+
3249
/// A `package:web`-based HTTP client that runs in the browser and is backed by
3350
/// [`window.fetch`](https://fetch.spec.whatwg.org/).
3451
///
@@ -44,7 +61,7 @@ BaseClient createClient() {
4461
class BrowserClient extends BaseClient {
4562
final _abortController = AbortController();
4663

47-
final String? _cacheMode;
64+
final CacheMode _cacheMode;
4865

4966
/// Create a new browser-based HTTP Client.
5067
///
@@ -53,12 +70,10 @@ class BrowserClient extends BaseClient {
5370
///
5471
/// For example:
5572
/// ```dart
56-
/// final client = BrowserClient(cacheMode: 'reload');
73+
/// final client = BrowserClient(cacheMode: CacheMode.reload);
5774
/// ```
58-
///
59-
/// Defaults to `default`.
60-
/// https://developer.mozilla.org/en-US/docs/Web/API/Request/cache
61-
BrowserClient([String? cacheMode]) : _cacheMode = cacheMode ?? 'default';
75+
BrowserClient({CacheMode cacheMode = CacheMode.defaultType})
76+
: _cacheMode = cacheMode;
6277

6378
/// Whether to send credentials such as cookies or authorization headers for
6479
/// cross-site requests.
@@ -84,7 +99,7 @@ class BrowserClient extends BaseClient {
8499
RequestInit(
85100
method: request.method,
86101
body: bodyBytes.isNotEmpty ? bodyBytes.toJS : null,
87-
cache: _cacheMode!,
102+
cache: _cacheMode.cacheType,
88103
credentials: withCredentials ? 'include' : 'same-origin',
89104
headers: {
90105
if (request.contentLength case final contentLength?)
@@ -199,18 +214,4 @@ Stream<List<int>> _readBody(BaseRequest request, Response response) async* {
199214
@JS()
200215
extension type _IterableHeaders._(JSObject _) implements JSObject {
201216
external void forEach(JSFunction fn);
202-
}
203-
204-
/// Caching modes for any http request in a browser.
205-
enum CacheMode {
206-
defaultType('default'),
207-
reload('reload'),
208-
noStore('no-store'),
209-
noCache('no-cache'),
210-
forceCache('force-cache'),
211-
onlyIfCached('only-if-cached');
212-
213-
final String cacheType;
214-
215-
const CacheMode(this.cacheType);
216-
}
217+
}

0 commit comments

Comments
 (0)