get method

Future get(
  1. String key, {
  2. Map<String, dynamic>? metadata,
})

Retrieve a value from the cache.

Returns null if not found or expired (based on hooks like TTL).

If macro get handlers are configured and key matches a pattern, automatically fetches and caches the data on cache miss.

Example:

final user = await cache.get('user:123');

Implementation

Future<dynamic> get(String key, {Map<String, dynamic>? metadata}) async {
  final ctx = PVCtx(
    cache: this,
    actionType: ActionType.get,
    initialKey: key,
    initialMeta: metadata ?? {},
  );
  await ctx.queue(_orderedGetHooks);

  // If cache miss and macro get handlers configured, try to fetch
  if (ctx.returnValue == null && macroGetHandlers.isNotEmpty) {
    for (final entry in macroGetHandlers.entries) {
      final pattern = entry.key;
      final fetchFn = entry.value;

      // Check if key matches pattern
      if (_matchesPattern(key, pattern)) {
        try {
          // Fetch the data
          final fetched = await fetchFn(key);

          if (fetched != null) {
            // Merge default macro get metadata with request metadata
            final fetchMetadata = {...macroGetDefaultMetadata, ...?metadata};

            // Cache the fetched data
            await put(key, fetched, metadata: fetchMetadata);
            return fetched;
          }
        } catch (e) {
          // If fetch fails, continue to next pattern
          continue;
        }
      }
    }
  }

  return ctx.returnValue;
}