iws_http_model 1.2.0
iws_http_model: ^1.2.0 copied to clipboard
Library for HTTP requests with the common operations CRUD, pagination and error handling.
example/main.dart
import 'package:iws_http/iws_http.dart';
import 'package:iws_http_model/iws_http_model.dart';
import 'package:iws_cache/iws_cache.dart';
class BookSearch {
final String kind;
final String id;
final String etag;
BookSearch(this.kind, this.id, this.etag);
factory BookSearch.fromJson(Map<String, dynamic> json) =>
BookSearch(json["kind"], json["id"], json["etag"]);
static Map<String, dynamic> toJson(BookSearch model) =>
{"kind": model.kind, "id": model.id, "etag": model.etag};
}
void main() async {
IwsHttp.setup(authority: 'googleapis.com', basePath: 'books/v1/');
final bookProvider = IwsHttpModel<BookSearch>(
path: 'volumes',
iwsHttp: IwsHttp(),
toJson: BookSearch.toJson,
fromJson: BookSearch.fromJson,
resultAttribute: 'items');
// Create a cache instance for API responses
final cache = IwsMemoryCache(
maxSize: 100,
evictionPolicy: EvictionPolicy.lru,
);
try {
// Example without cache
print('Making first request (without cache)...');
List<BookSearch> books = await bookProvider
.fetch(queryParameters: {'q': '{http}', 'maxResults': '5'});
print('Found ${books.length} books about http (no cache).');
// Create cache configurations
final standardCacheConfig = CacheConfig.standard(
cache: cache,
ttl: const Duration(minutes: 10),
);
final staleWhileRevalidateConfig = CacheConfig.staleWhileRevalidate(
cache: cache,
ttl: const Duration(minutes: 10),
);
// Example with cache - first call will cache the result
print('\nMaking first request with cache...');
List<BookSearch> cachedBooks = await bookProvider.fetch(
queryParameters: {'q': '{flutter}', 'maxResults': '5'},
cacheConfig: standardCacheConfig);
print('Found ${cachedBooks.length} books about flutter (cached).');
// Second call with same parameters will use cache
print('\nMaking second request with same parameters (should use cache)...');
List<BookSearch> cachedBooks2 = await bookProvider.fetch(
queryParameters: {'q': '{flutter}', 'maxResults': '5'},
cacheConfig: standardCacheConfig);
print('Found ${cachedBooks2.length} books about flutter (from cache).');
// Example with paginated data (without cache)
print('\nMaking paginated request without cache...');
PaginatedData<BookSearch> result =
await bookProvider.fetchPaginated(queryParameters: {'q': '{dart}'});
print(
'Paginated request - Number of books about dart: ${result.meta.total}.');
// Example with paginated data using cache
print('\nMaking first paginated request with cache...');
PaginatedData<BookSearch> cachedPaginatedResult =
await bookProvider.fetchPaginated(
queryParameters: {'q': '{python}', 'maxResults': '3'},
page: 1,
cacheConfig: CacheConfig.standard(
cache: cache,
ttl: const Duration(minutes: 15),
));
print(
'Found ${cachedPaginatedResult.data.length} books about python (page ${cachedPaginatedResult.meta.currentPage}) - cached.');
// Second paginated call with same parameters will use cache
print(
'\nMaking second paginated request with same parameters (should use cache)...');
PaginatedData<BookSearch> cachedPaginatedResult2 =
await bookProvider.fetchPaginated(
queryParameters: {'q': '{python}', 'maxResults': '3'},
page: 1,
cacheConfig: CacheConfig.standard(
cache: cache,
ttl: const Duration(minutes: 15),
));
print(
'Found ${cachedPaginatedResult2.data.length} books about python (page ${cachedPaginatedResult2.meta.currentPage}) - from cache.');
// Example with forceRefresh - ignores cache and forces fresh data from server
print('\nDemonstrating forceRefresh functionality...');
// Create a forceRefresh config
final forceRefreshConfig = CacheConfig.forceRefresh(
cache: cache,
ttl: const Duration(minutes: 10),
);
print('Forcing refresh for flutter books (ignoring cache)...');
List<BookSearch> refreshedBooks = await bookProvider.fetch(
queryParameters: {'q': '{flutter}', 'maxResults': '5'},
cacheConfig: forceRefreshConfig);
print(
'Found ${refreshedBooks.length} books about flutter (fresh from server, cache updated).');
// Example with staleWhileRevalidate - returns cached data immediately and updates in background
print('\nDemonstrating stale-while-revalidate functionality...');
// First, ensure we have data in cache
await bookProvider.fetch(
queryParameters: {'q': 'javascript', 'maxResults': '3'},
cacheConfig: standardCacheConfig);
// Now use staleWhileRevalidate - this will return cached data immediately
// and update the cache in the background
final stopwatch = Stopwatch()..start();
List<BookSearch> staleBooks = await bookProvider.fetch(
queryParameters: {'q': 'javascript', 'maxResults': '3'},
cacheConfig: staleWhileRevalidateConfig);
stopwatch.stop();
print(
'Stale-while-revalidate returned ${staleBooks.length} books in ${stopwatch.elapsedMilliseconds}ms');
print(
'(Data returned from cache immediately, fresh data being fetched in background)');
// Demonstrate with paginated data
print('\nStale-while-revalidate with pagination...');
await bookProvider.fetchPaginated(
queryParameters: {'q': 'react', 'maxResults': '2'},
page: 1,
cacheConfig: standardCacheConfig);
final stopwatch2 = Stopwatch()..start();
PaginatedData<BookSearch> stalePaginated = await bookProvider
.fetchPaginated(
queryParameters: {'q': 'react', 'maxResults': '2'},
page: 1,
cacheConfig: staleWhileRevalidateConfig);
stopwatch2.stop();
print(
'Stale-while-revalidate pagination returned ${stalePaginated.data.length} books in ${stopwatch2.elapsedMilliseconds}ms');
print(
'(Cached paginated data returned immediately, background update in progress)');
// Get cache statistics
final stats = await cache.getStats();
print('\nCache statistics:');
print(' Items in cache: ${stats.itemCount}');
print(' Hit ratio: ${stats.hitRatio.toStringAsFixed(2)}');
} on ApiException catch (e) {
print('Request failed with status: ${e.httpCode}.');
} finally {
// Always close the cache when done
await cache.close();
}
}