Axios HTTP Client Refactoring with Cache

evening folks. doing a bit of refactoring with an axios http client and a cache that holds the current access token. originally i had a completely separate service for just the cache but that seemed wasteful on account of it only being needed by the http client. the http client is injected as a service to my custom app runtime and passed to all my services as the authorized http client. am i going about initializing the cache the right way here? i should i create it completely outside of this function and reference it instead?

import axios from "axios";
import { Effect, pipe } from "effect";
import { makeCache } from "./http-client.cache";
import type { MakeServiceArgs } from "./http-client.types";

export function makeService({ basePath, cacheKey }: MakeServiceArgs) {
  return Effect.gen(function* ($) {
    const cache = yield* $(makeCache);

    const instance = axios.create({ baseURL: basePath });

    instance.interceptors.request.use(async (config) => {
      return await Effect.runPromise(
        pipe(
          cache.get(cacheKey),
          Effect.tap(({ accessToken }) => (config.headers.Authorization = `Bearer ${accessToken}`)),
          Effect.zipRight(Effect.succeed(config)),
          Effect.catchAll(() => Effect.succeed(config)),
        ),
      );
    });

    return { instance };
  });
}
Was this page helpful?