mirror of
https://github.com/nicotsx/zerobyte.git
synced 2026-04-18 05:47:31 -04:00
* refactor: move to tanstack start * refactor: auth flow & volumes * refactor: repo & snapshot details * refactor: backups, create repo, volumes * refactor: create volume & restore snapshot * refactor: notifications * refactor: settings * refactor: breadcrumbs * fix: ts issues * refactor: prod deployment * fix: import css production * refactor: nitro build * refactor: winston -> consola * fix: memory leak is sse events cleanup * fix: cli usage * chore: remove rr routes file * refactor: pr feedbacks * refactor: patch api client to have a global client per call * refactor: pr feedbacks * fix(dockerfile): add explicit port * fix(e2e): healthcheck under /api
62 lines
1.7 KiB
TypeScript
62 lines
1.7 KiB
TypeScript
import type { Config } from "~/client/api-client/client";
|
|
import { createClient, createConfig } from "~/client/api-client/client";
|
|
|
|
export type RequestClient = ReturnType<typeof createClient>;
|
|
|
|
type RequestClientStore = {
|
|
getStore: () => RequestClient | undefined;
|
|
run: <T>(client: RequestClient, fn: () => T) => T;
|
|
};
|
|
|
|
type AsyncLocalStorageConstructor = new <T>() => {
|
|
getStore: () => T | undefined;
|
|
run: <R>(store: T, callback: () => R) => R;
|
|
};
|
|
|
|
let requestClientStore: RequestClientStore | undefined;
|
|
let requestClientStorePromise: Promise<RequestClientStore | undefined> | undefined;
|
|
|
|
const ASYNC_HOOKS_MODULE = "node:async_hooks";
|
|
|
|
const loadRequestClientStore = async (): Promise<RequestClientStore | undefined> => {
|
|
if (typeof window !== "undefined") {
|
|
return undefined;
|
|
}
|
|
|
|
if (!requestClientStorePromise) {
|
|
requestClientStorePromise = (async () => {
|
|
const asyncHooksModule = (await import(/* @vite-ignore */ ASYNC_HOOKS_MODULE)) as {
|
|
AsyncLocalStorage: AsyncLocalStorageConstructor;
|
|
};
|
|
requestClientStore = new asyncHooksModule.AsyncLocalStorage<RequestClient>();
|
|
return requestClientStore;
|
|
})();
|
|
}
|
|
|
|
return requestClientStorePromise;
|
|
};
|
|
|
|
export function getRequestClient(): RequestClient {
|
|
const client = requestClientStore?.getStore();
|
|
|
|
if (!client) {
|
|
throw new Error("No request client available");
|
|
}
|
|
|
|
return client;
|
|
}
|
|
|
|
export async function runWithRequestClient<T>(client: RequestClient, fn: () => T): Promise<T> {
|
|
const store = await loadRequestClientStore();
|
|
|
|
if (!store) {
|
|
return fn();
|
|
}
|
|
|
|
return store.run(client, fn);
|
|
}
|
|
|
|
export function createRequestClient(config: Config): RequestClient {
|
|
return createClient(createConfig(config));
|
|
}
|