Files
sendou.ink/app/utils/request-context.server.ts
2026-09-20 16:05:34 +03:00

27 lines
932 B
TypeScript

import { AsyncLocalStorage } from "node:async_hooks";
// TODO: this is only needed for our current hacky toast setup, once a proper one in place this middleware can be deleted
interface RequestContext {
/** Normalized (single-fetch `.data` suffix and internal search params removed) */
url: URL;
}
const requestContextAsyncLocalStorage = new AsyncLocalStorage<RequestContext>();
/** Runs `fn` with the request context available to helpers (e.g. toast redirects) lacking the request. */
export function runWithRequestContext<T>(
context: RequestContext,
fn: () => T,
): T {
return requestContextAsyncLocalStorage.run(context, fn);
}
/** Pathname and search params of the current request, `undefined` outside a request context. */
export function currentRequestPath(): string | undefined {
const url = requestContextAsyncLocalStorage.getStore()?.url;
if (!url) return undefined;
return `${url.pathname}${url.search}`;
}