Shared State and Cookie Management in TypeScript HttpClient Implementation

evening folks, was hoping for a little guidance on what im doing here. would i be correct in assuming that any other services mutating the cookiesRef will have an immediate effect for other consumers of the companyClient? Is there anything thats standing out as a red flag in this implementation so far? been trying to peacemeal together a readable solution from everyone elses conversations in this discord and the docs...

export const makeLiveCompanyHttpClient = Effect.gen(function* () {
  const config = yield* ConfigStore;
  const defaultClient = yield* HttpClient.HttpClient;
  const cookiesRef = yield* Ref.make(Cookies.empty);

  // Testing to make sure bearer token is picked up (it is)
  yield* Ref.update(cookiesRef, Cookies.unsafeSet("AccessToken", "secretSquirrel"));

  function cookieToBearerToken(request: HttpClientRequest.HttpClientRequest) {
    return pipe(
      cookiesRef.get,
      Effect.flatMap(({ cookies }) => pipe(cookies, Record.get("AccessToken"))),
      Effect.map((cookie) => cookie.value),
      Effect.match({
        onFailure: () => request,
        onSuccess: (value) => pipe(request, HttpClientRequest.bearerToken(value)),
      }),
    );
  }

  const client = pipe(
    defaultClient,
    HttpClient.withCookiesRef(cookiesRef),
    HttpClient.mapRequest(HttpClientRequest.prependUrl(config.baseUrl)),
    HttpClient.mapRequest(HttpClientRequest.acceptJson),
    HttpClient.mapRequest(HttpClientRequest.accept("text/html;q=0.9")),
    HttpClient.mapRequestEffect(cookieToBearerToken),
    HttpClient.followRedirects(3),
    HttpClient.filterStatusOk,
    HttpClient.retry({
      schedule: Schedule.exponential("1.5 seconds", 1.5),
      times: 3,
    }),
  );

  return { client, cookiesRef };
});
Was this page helpful?