refactor(housekeeping): reuse request capability context

This commit is contained in:
simoleo89
2026-08-26 21:20:12 +02:00
parent cc6bb9a9a3
commit edc165ba8d
5 changed files with 134 additions and 8 deletions
@@ -1,14 +1,29 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const { auth, getAdminContext, staleActor } = vi.hoisted(() => ({
auth: vi.fn(),
getAdminContext: vi.fn(),
staleActor: { id: 9, username: "stale-session", rank: 1 },
}));
const { auth, getAdminContext, resetRequestCache, staleActor, wrapCache } =
vi.hoisted(() => {
const resetters: (() => void)[] = [];
vi.mock("react", () => ({
cache: <T extends (...args: never[]) => unknown>(callback: T) => callback,
}));
return {
auth: vi.fn(),
getAdminContext: vi.fn(),
resetRequestCache: () => {
resetters.forEach((reset) => {
reset();
});
},
staleActor: { id: 9, username: "stale-session", rank: 1 },
wrapCache: (callback: () => Promise<unknown>) => {
let value: Promise<unknown> | undefined;
resetters.push(() => {
value = undefined;
});
return () => (value ??= callback());
},
};
});
vi.mock("react", () => ({ cache: wrapCache }));
vi.mock("@/lib/auth", () => ({ auth }));
vi.mock("@/lib/db", () => {
@@ -16,11 +31,14 @@ vi.mock("@/lib/db", () => {
});
vi.mock("@/lib/permissions", () => ({ getAdminContext }));
import { requireHousekeepingCapability } from "@/lib/admin/guard";
import { auth as mockedAuth } from "@/lib/auth";
import { anyCapability } from "./contracts";
import { getHousekeepingCapabilityContext } from "./server-capability-context";
describe("getHousekeepingCapabilityContext", () => {
beforeEach(() => {
resetRequestCache();
vi.clearAllMocks();
auth.mockResolvedValue({ user: staleActor });
getAdminContext.mockResolvedValue({
@@ -53,4 +71,12 @@ describe("getHousekeepingCapabilityContext", () => {
expect(getAdminContext).toHaveBeenCalledTimes(1);
expect(mockedAuth).not.toHaveBeenCalled();
});
it("loads the capability context once for shell, page, and command preflight", async () => {
await getHousekeepingCapabilityContext();
await getHousekeepingCapabilityContext();
await requireHousekeepingCapability(anyCapability("admin.users.view"));
expect(getAdminContext).toHaveBeenCalledTimes(1);
});
});