pageConfigProvider top-level property

StreamProviderFamily<UiNode, String> pageConfigProvider
final

Reactive stream provider managing page config fetches, caching, and SSE streams.

Implementation

final pageConfigProvider =
    StreamProvider.family<UiNode, String>((ref, slug) async* {
  final client = ref.watch(sanityClientProvider);

  SanityRealtimeListener? listener;
  ref.onDispose(() => listener?.dispose());

  bool hasEmitted = false;

  // 1. Load from Hive cache
  final cached = ConfigCache.load(slug);
  if (cached != null) {
    hasEmitted = true;
    yield UiNode.fromPageDocument(cached);
  }

  // 2. Fetch fresh document from Sanity
  try {
    final fresh = await client.fetchPageConfig(slug);
    if (fresh != null) {
      hasEmitted = true;
      await ConfigCache.save(slug, fresh);
      yield UiNode.fromPageDocument(fresh);
    }
  } catch (e) {
    if (!hasEmitted) rethrow;
  }

  if (!hasEmitted) {
    throw Exception(
      'No Page Config document found in Sanity for slug "$slug".\n'
      'Please create and publish a Page Config document with slug "$slug" in Sanity Studio.',
    );
  }

  // 3. Connect realtime SSE stream listener
  final query = '*[_type == "pageConfig" && slug.current == "$slug"][0]';
  listener = SanityRealtimeListener(client: client, groqQuery: query);
  await listener.start();

  await for (final result in listener.updates) {
    await ConfigCache.save(slug, result);
    yield UiNode.fromPageDocument(result);
  }
});