Effect CommunityEC
Effect Community15mo ago
29 replies
Jambudipa

Memoising effects

I am creating an HttpRpcResovler but need to memoise it, because of course I do not want to recreate it for every request.

I have this base code:
const makeClient = Effect.gen(function* () {
  const client = yield* HttpClient.HttpClient;
  return HttpRpcResolver.make<AppRouter>(
    client.pipe(
      HttpClient.mapRequest(HttpClientRequest.prependUrl('http://localhost:3000/rpc'))
    )
  ).pipe(RpcResolver.toClient);
});

const fetchDataFunction = () => {
  return Effect.runPromise(
    Effect.gen(function* () {
      const client = yield* makeClient;
      const data = yield* client(new Search());
      return data;
    }).pipe(
      Effect.provide(FetchHttpClient.layer)
    )
  );
};

My various attempts at caching it have yielded various problems:
const fetchDataFunction = () => {
  return Effect.runPromise(
    Effect.gen(function* () {
      const client = yield* Effect.cached(makeClient); // <!-- cache here
      const data = yield* client(new Search());
      return data;
    }).pipe(
      Effect.provide(FetchHttpClient.layer)
    )
  );
};

This gives rise to this type error:
TS2345: Argument of type Effect<any, unknown, unknown> is not assignable to parameter of type Effect<any, unknown, never>
Type unknown is not assignable to type never

It changes the type from
const client: <Req extends Search>(request: Req) => Rpc.Result<Req, never>

to
any
.

In this context, how do I help the type system? Surely not the dreaded as?
Was this page helpful?