Skip to content

Cache Handling with CacheHandlerSpecs

Declarative Cache Management

Use CacheHandlerSpecs for declarative cache operations instead of imperative handler registration.

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));
}),
);

Register during client initialization:

@riverpod
GqlClient 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,
);
}
  1. Identifiers: Items must have id and __typename for Ferry cache nodes
  2. JSON-compatible types: Use build.yaml custom type mapping for scalars
  3. Request ID consistency: requestId in mapToCachedRequest must match the original query