getCachedOrFetch static method
Generic helper: check cache → fetch → cache result.
Implementation
static Future<HttpResponse<dynamic>> getCachedOrFetch({
required String url,
Map<String, String>? headers,
dynamic body,
required bool forceUpdate,
required Duration ttl,
required Future<HttpResponse<dynamic>> Function() fetchFn,
}) async {
final cacheKey = generateCacheKeyForRequest(
url: url,
headers: headers,
body: body,
);
// Check cache first
if (!forceUpdate) {
final cachedResponse = await getCachedResponse(
cacheKey: cacheKey,
forceUpdate: forceUpdate,
);
if (cachedResponse != null) {
return cachedResponse;
}
}
// Fetch fresh data
final freshResponse = await fetchFn();
// Cache if successful
cacheIfSuccessful(
cacheKey: cacheKey,
response: freshResponse,
ttl: ttl,
);
return freshResponse;
}