Effect CommunityEC
Effect Community3y ago
32 replies
sandromaglione

Implementing a Cache using Cache.make and understanding the lookup function

How is implemented a Cache using Cache.make?

Specifically, it's not clear to me how lookup works. I tried with this:
const globalCache = new Map<number, Pokemon>();

const cacheSource = Cache.make({
  capacity: globalThis.Number.MAX_SAFE_INTEGER,
  timeToLive: Infinity,
  lookup: (key: number) => Effect.fromNullable(globalCache.get(key)),
});


And then using the cache:
Effect.gen(function* (_) {
  const cache = yield* _(cacheSource);
  const inCache = yield* _(cache.get(20), Effect.either);
  if (Either.isRight(inCache)) {
    yield* _(Console.info("Got a pokemon (cache)", inCache.right));
    return;
  }

  const pokemon = yield* _(getPokemon(20));

  yield* _(Console.info("Got a pokemon", pokemon));
  yield* _(cache.set(20, pokemon));
})
  .pipe(
    Effect.catchTags({
      PokemonClientError: (error) => Console.error(error.reason, error.error),
    }),
    Effect.repeat(
      Schedule.recurs(5).pipe(Schedule.addDelay(() => Duration.millis(1000)))
    ),
    Effect.runPromise
  )


But this does not seem to work (the cache is always empty). I think I am making some mistake in Cache.make.
Was this page helpful?