ifNotCachedStatic static method

Future ifNotCachedStatic(
  1. HHPayloadI payload,
  2. Future computeValue(), {
  3. bool cacheOnNullValues = false,
})

Gets cached value or computes and caches it if not found. Set cacheOnNullValues to control whether null results are cached.

Implementation

static Future<dynamic> ifNotCachedStatic(
  HHPayloadI payload,
  Future<dynamic> Function() computeValue, {
  bool cacheOnNullValues = false,
}) async {
  final ctx = HHCtx(payload);

  // Try to get existing value
  final existing = await ctx.control.emit(
    TriggerType.valueRead.name,
    action: (ctx) async {
      return await ctx.access.storeGet(ctx.payload.key!);
    },
    handleCtrlException: true,
  );

  if (existing != null) {
    return existing;
  }

  // Compute new value
  final newValue = await computeValue();
  if (newValue == null && !cacheOnNullValues) {
    return null;
  }
  // Store it
  await ctx.control.emit(
    TriggerType.valueWrite.name,
    action: (ctx) async {
      await ctx.access.storePut(ctx.payload.key!, newValue);
      if ((ctx as HHCtx).config.usesMeta && ctx.payload.metadata != null) {
        await ctx.access.metaPut(ctx.payload.key!, ctx.payload.metadata!);
      }
    },
    handleCtrlException: true,
  );

  return newValue;
}