Route Cache System
This guide will walk you through the steps to use caching in your Finch application routes. Caching helps improve performance by storing HTTP responses either in memory or on your file system, drastically reducing the response time for repetitive requests.
What is Route Cache?
The RouteCache class extends the standard FinchRoute by adding caching capabilities. Instead of executing the route handler for every request, Finch intercepts the route and serves the previously cached response if it exists and hasn't expired.
How to use Route Cache
Finch provides a convenient extension on FinchRoute called .cache() that easily wraps your existing routes with caching functionality.
Example of caching a basic route:
FinchRoute(
path: '/api/data',
index: () async {
// Some heavy processing or database query
await Future.delayed(Duration(seconds: 2));
return Context.rq.renderJson(data: {'message': 'Heavy data loaded'});
},
).cache(
cacheDuration: Duration(minutes: 5), // Cache valid for 5 minutes
cacheSource: CacheSource.memory, // Store cache in memory (RAM)
);
Configuration Options
When you call .cache() (or create a RouteCache directly), you can configure its behavior with these properties:
cacheDuration: TheDurationfor which the cache entry is considered valid. After this time, the cache expires and the original handler will run again on the next request. Default is10 minutes.cacheSource: Where the cache is stored. Can beCacheSource.memory(default) for fast RAM caching orCacheSource.filefor persistent file-based caching.cacheType: A list ofCacheParamspecifying what parts of the request form the unique cache key. Default is[CacheParam.method, CacheParam.path].
Cache Types (CacheParam)
You can define how the cache key is constructed by using the CacheParam enum. This ensures that different requests don't mistakenly serve the same cached response.
CacheParam.path: (Required) The request URI path (e.g.,/api/data).CacheParam.method: The HTTP method (e.g.,GET,POST).CacheParam.query: The URL query string (e.g.,?page=1&limit=10).CacheParam.data: The request body data.
Example with specific Cache Types:
If you have a search endpoint that takes query parameters, you must include CacheParam.query in your cacheType so that ?q=apple and ?q=orange generate different cache entries.
FinchRoute(
path: '/search',
index: () async {
final query = Context.rq.getQuery('q');
return Context.rq.renderJson(data: {'results': 'Found results for $query'});
},
).cache(
cacheType: [CacheParam.path, CacheParam.method, CacheParam.query],
);
Cache Sources (CacheSource)
CacheSource.memory: The cache is stored in a staticMapin memory. This is the fastest caching method but will be cleared if your server restarts.CacheSource.file: The cache is stored as JSON files on the local disk. The directory is determined byFinchApp.config.pathCache. This survives application restarts but requires disk I/O.
Managing Cache
You can clear all the cached responses globally across your application. This is especially useful during application updates or data migrations.
import 'package:finch/src/router/route_cache.dart';
void main() async {
// Clear all cache (both memory and file system)
await RouteCache.clearAllCache();
}
By leveraging RouteCache, you can greatly scale the performance of your Finch application endpoints without adding complex external dependencies!