Cache Handling with CacheHandlerSpecs
Declarative Cache Management
Use CacheHandlerSpecs for declarative cache operations instead of imperative handler registration.
Cache Handling with CacheHandlerSpecs
Section titled “Cache Handling with CacheHandlerSpecs”CacheHandlerSpecs Types
Section titled “CacheHandlerSpecs Types”Clear: Evict a Specific Cached Request
Section titled “Clear: Evict a Specific Cached Request”CacheHandlerSpecs.clear( mapToCachedRequest: Convertor((mutationRequest) { return GQueryAttendeeReq((b) => b ..requestId = 'attendee_detail_${mutationRequest.vars.id}'); }),);ClearAll: Evict All Cached Requests of a Type
Section titled “ClearAll: Evict All Cached Requests of a Type”CacheHandlerSpecs.clearAll( mapToCachedRequest: Convertor((mutationRequest) { return GQueryAttendeeListReq((b) => b..requestId = 'attendee_list'); }),);Merge: Update Cached Data with Mutation Response
Section titled “Merge: Update Cached Data with Mutation Response”CacheHandlerSpecs.merge( mapToCachedRequest: Convertor((mutationRequest) { return GQueryAttendeeListReq((b) => b..requestId = 'attendee_list'); }), mapResponse: Convertor((mutationData) => mutationData.attendeeSave), mergeCachedData: Convertor(((oldCachedData, newMutationData)) { final items = oldCachedData.attendee!.attendeeItems!.toList(); final existingIndex = items.indexWhere((i) => i?.id == newMutationData.id); if (existingIndex >= 0) { items[existingIndex] = newMutationData; } else { items.insert(0, newMutationData); } return oldCachedData.rebuild((b) => b..attendee.attendeeItems.replace(items)); }),);Registering Cache Specs
Section titled “Registering Cache Specs”Register during client initialization:
@riverpodGqlClient gqlClient(Ref ref) { final cache = Cache(); final specs = SetMultimap<Type, CacheHandlerSpecs>();
specs.add(GMutateAttendeeSaveReq, attendeeUpsertCacheSpec); specs.add(GMutateAttendeeDeleteReq, attendeeDeleteCacheSpec);
return GqlClient( link: Link.from([ UpdateCacheTypedLink(cache: cache, cacheHandlersSpecs: specs), HttpLink('https://api.example.com/graphql'), ]), cache: cache, );}Key Caching Requirements
Section titled “Key Caching Requirements”- Identifiers: Items must have
idand__typenamefor Ferry cache nodes - JSON-compatible types: Use
build.yamlcustom type mapping for scalars - Request ID consistency:
requestIdinmapToCachedRequestmust match the original query