Skip to content

Initialize GraphQL Client

Convertor-Compatible Client Setup

Configure the Ferry client with UpdateCacheTypedLink for declarative cache management.

The Ferry GraphQL client must be configured with the UpdateCacheTypedLink to support the Convertor pattern’s declarative cache management via CacheHandlerSpecs.

@riverpod
GqlClient gqlClient(Ref ref) {
final cache = Cache();
// Collect CacheHandlerSpecs from all features
final cacheHandlersSpecs = SetMultimap<Type, CacheHandlerSpecs>();
_registerNotificationCacheSpecs(cacheHandlersSpecs);
_registerChatCacheSpecs(cacheHandlersSpecs);
final link = Link.from([
UpdateCacheTypedLink(
cache: cache,
cacheHandlersSpecs: cacheHandlersSpecs,
),
WebSocketLink(
'wss://api.example.com/graphql',
autoReconnect: true,
),
HttpLink('https://api.example.com/graphql'),
]);
return GqlClient(link: link, cache: cache);
}

Set up custom type mapping for GQL scalar types:

targets:
$default:
builders:
ferry_generator:
options:
schema: lib/src/core/remote/gql/schema.graphql
type_overrides:
DateTime:
name: DateTime
import: 'dart:core'
JSON:
name: Map<String, dynamic>
import: 'dart:core'

See Ferry Custom Type Mapping for the full configuration guide.

Each feature registers its CacheHandlerSpecs:

void _registerNotificationCacheSpecs(
SetMultimap<Type, CacheHandlerSpecs> specs,
) {
specs.add(
GMutateNotificationSaveReq,
CacheHandlerSpecs.merge(
cacheHandlerKey: 'notificationUpsert',
mapToCachedRequest: Convertor((request) =>
GQueryNotificationReq((b) => b..requestId = 'notification_list')),
mapResponse: Convertor((data) => data.notificationSave),
mergeCachedData: Convertor(((old, new_)) {
final items = old.notification!.notificationItems!.toList();
items.insert(0, new_);
return old.rebuild((b) =>
b..notification.notificationItems.replace(items));
}),
),
);
}
  • UpdateCacheTypedLink must be first in the link chain to intercept all responses
  • CacheHandlerSpecs are registered per mutation request type
  • The client is shared via a single @riverpod provider
  • WebSocket link handles subscriptions; HTTP link handles queries and mutations