add tests on refactor
This commit is contained in:
@@ -14,6 +14,7 @@ describe("Auth Enabled Toggle Authorization", () => {
|
||||
let csrfHeaderName: string;
|
||||
let csrfToken: string;
|
||||
let regularUserToken: string;
|
||||
let adminUserToken: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
setupTestDb();
|
||||
@@ -58,6 +59,26 @@ describe("Auth Enabled Toggle Authorization", () => {
|
||||
signOptions
|
||||
);
|
||||
|
||||
const admin = await prisma.user.create({
|
||||
data: {
|
||||
email: "admin-user@test.local",
|
||||
passwordHash,
|
||||
name: "Admin User",
|
||||
role: "ADMIN",
|
||||
isActive: true,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
},
|
||||
});
|
||||
|
||||
adminUserToken = jwt.sign(
|
||||
{ userId: admin.id, email: admin.email, type: "access" },
|
||||
config.jwtSecret,
|
||||
signOptions
|
||||
);
|
||||
|
||||
const agent = request.agent(app);
|
||||
const csrfRes = await agent
|
||||
.get("/csrf-token")
|
||||
@@ -91,4 +112,27 @@ describe("Auth Enabled Toggle Authorization", () => {
|
||||
expect(response.status).toBe(403);
|
||||
expect(response.body?.message).toContain("Admin access required");
|
||||
});
|
||||
|
||||
it("applies auth mode change immediately for subsequent requests", async () => {
|
||||
const warmStatusResponse = await request(app)
|
||||
.get("/auth/status")
|
||||
.set("User-Agent", userAgent);
|
||||
expect(warmStatusResponse.status).toBe(200);
|
||||
expect(warmStatusResponse.body?.authEnabled).toBe(true);
|
||||
|
||||
const toggleResponse = await request(app)
|
||||
.post("/auth/auth-enabled")
|
||||
.set("User-Agent", userAgent)
|
||||
.set("Authorization", `Bearer ${adminUserToken}`)
|
||||
.set(csrfHeaderName, csrfToken)
|
||||
.send({ enabled: false });
|
||||
expect(toggleResponse.status).toBe(200);
|
||||
expect(toggleResponse.body?.authEnabled).toBe(false);
|
||||
|
||||
const drawingsResponse = await request(app)
|
||||
.get("/drawings")
|
||||
.set("User-Agent", userAgent);
|
||||
expect(drawingsResponse.status).toBe(200);
|
||||
expect(Array.isArray(drawingsResponse.body?.drawings)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -342,6 +342,7 @@ export const createAuthRouter = (deps: CreateAuthRouterDeps): express.Router =>
|
||||
isMissingRefreshTokenTableError,
|
||||
bootstrapUserId: BOOTSTRAP_USER_ID,
|
||||
defaultSystemConfigId: DEFAULT_SYSTEM_CONFIG_ID,
|
||||
clearAuthEnabledCache: authModeService.clearAuthEnabledCache,
|
||||
});
|
||||
|
||||
registerAdminRoutes({
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
|
||||
import { PrismaClient } from "../generated/client";
|
||||
import {
|
||||
BOOTSTRAP_USER_ID,
|
||||
DEFAULT_SYSTEM_CONFIG_ID,
|
||||
createAuthModeService,
|
||||
} from "./authMode";
|
||||
|
||||
const createPrismaMock = () =>
|
||||
({
|
||||
systemConfig: {
|
||||
findUnique: vi.fn(),
|
||||
upsert: vi.fn(),
|
||||
},
|
||||
user: {
|
||||
upsert: vi.fn(),
|
||||
},
|
||||
}) as unknown as PrismaClient;
|
||||
|
||||
describe("authMode service", () => {
|
||||
let now = 1_000_000;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.spyOn(Date, "now").mockImplementation(() => now);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("caches authEnabled reads within TTL", async () => {
|
||||
const prisma = createPrismaMock();
|
||||
const findUnique = prisma.systemConfig.findUnique as unknown as ReturnType<typeof vi.fn>;
|
||||
const upsert = prisma.systemConfig.upsert as unknown as ReturnType<typeof vi.fn>;
|
||||
findUnique
|
||||
.mockResolvedValueOnce({ authEnabled: true })
|
||||
.mockResolvedValueOnce({ authEnabled: false });
|
||||
|
||||
const service = createAuthModeService(prisma, { authEnabledTtlMs: 5000 });
|
||||
|
||||
await expect(service.getAuthEnabled()).resolves.toBe(true);
|
||||
|
||||
now += 1000;
|
||||
await expect(service.getAuthEnabled()).resolves.toBe(true);
|
||||
expect(findUnique).toHaveBeenCalledTimes(1);
|
||||
|
||||
now += 6000;
|
||||
await expect(service.getAuthEnabled()).resolves.toBe(false);
|
||||
expect(findUnique).toHaveBeenCalledTimes(2);
|
||||
expect(upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("clears auth cache when requested", async () => {
|
||||
const prisma = createPrismaMock();
|
||||
const findUnique = prisma.systemConfig.findUnique as unknown as ReturnType<typeof vi.fn>;
|
||||
const upsert = prisma.systemConfig.upsert as unknown as ReturnType<typeof vi.fn>;
|
||||
findUnique.mockResolvedValue({ authEnabled: true });
|
||||
|
||||
const service = createAuthModeService(prisma);
|
||||
await service.getAuthEnabled();
|
||||
service.clearAuthEnabledCache();
|
||||
await service.getAuthEnabled();
|
||||
|
||||
expect(findUnique).toHaveBeenCalledTimes(2);
|
||||
expect(upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("falls back to upsert when system config row is missing", async () => {
|
||||
const prisma = createPrismaMock();
|
||||
const findUnique = prisma.systemConfig.findUnique as unknown as ReturnType<typeof vi.fn>;
|
||||
const upsert = prisma.systemConfig.upsert as unknown as ReturnType<typeof vi.fn>;
|
||||
findUnique.mockResolvedValue(null);
|
||||
upsert.mockResolvedValue({ authEnabled: false });
|
||||
|
||||
const service = createAuthModeService(prisma);
|
||||
await expect(service.getAuthEnabled()).resolves.toBe(false);
|
||||
|
||||
expect(findUnique).toHaveBeenCalledTimes(1);
|
||||
expect(upsert).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("creates/bootstrap user via upsert", async () => {
|
||||
const prisma = createPrismaMock();
|
||||
const userUpsert = prisma.user.upsert as unknown as ReturnType<typeof vi.fn>;
|
||||
userUpsert.mockResolvedValue({
|
||||
id: BOOTSTRAP_USER_ID,
|
||||
email: "bootstrap@excalidash.local",
|
||||
name: "Bootstrap Admin",
|
||||
role: "ADMIN",
|
||||
isActive: false,
|
||||
mustResetPassword: true,
|
||||
username: null,
|
||||
});
|
||||
|
||||
const service = createAuthModeService(prisma);
|
||||
const bootstrapUser = await service.getBootstrapActingUser();
|
||||
|
||||
expect(bootstrapUser.id).toBe(BOOTSTRAP_USER_ID);
|
||||
expect(userUpsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { id: BOOTSTRAP_USER_ID },
|
||||
create: expect.objectContaining({
|
||||
id: BOOTSTRAP_USER_ID,
|
||||
email: "bootstrap@excalidash.local",
|
||||
role: "ADMIN",
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("ensures system config defaults", async () => {
|
||||
const prisma = createPrismaMock();
|
||||
const upsert = prisma.systemConfig.upsert as unknown as ReturnType<typeof vi.fn>;
|
||||
upsert.mockResolvedValue({ authEnabled: false });
|
||||
|
||||
const service = createAuthModeService(prisma);
|
||||
await service.ensureSystemConfig();
|
||||
|
||||
expect(upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { id: DEFAULT_SYSTEM_CONFIG_ID },
|
||||
create: expect.objectContaining({
|
||||
id: DEFAULT_SYSTEM_CONFIG_ID,
|
||||
authEnabled: false,
|
||||
registrationEnabled: false,
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -17,6 +17,13 @@ export const createAuthModeService = (
|
||||
const authEnabledTtlMs = options?.authEnabledTtlMs ?? 5000;
|
||||
let authEnabledCache: AuthEnabledCache | null = null;
|
||||
|
||||
const getSystemConfigAuthEnabled = async () => {
|
||||
return prisma.systemConfig.findUnique({
|
||||
where: { id: DEFAULT_SYSTEM_CONFIG_ID },
|
||||
select: { authEnabled: true },
|
||||
});
|
||||
};
|
||||
|
||||
const ensureSystemConfig = async () => {
|
||||
return prisma.systemConfig.upsert({
|
||||
where: { id: DEFAULT_SYSTEM_CONFIG_ID },
|
||||
@@ -38,6 +45,12 @@ export const createAuthModeService = (
|
||||
return authEnabledCache.value;
|
||||
}
|
||||
|
||||
const existingSystemConfig = await getSystemConfigAuthEnabled();
|
||||
if (existingSystemConfig) {
|
||||
authEnabledCache = { value: existingSystemConfig.authEnabled, fetchedAt: now };
|
||||
return existingSystemConfig.authEnabled;
|
||||
}
|
||||
|
||||
const systemConfig = await ensureSystemConfig();
|
||||
authEnabledCache = { value: systemConfig.authEnabled, fetchedAt: now };
|
||||
return systemConfig.authEnabled;
|
||||
|
||||
@@ -56,6 +56,7 @@ type RegisterCoreRoutesDeps = {
|
||||
isMissingRefreshTokenTableError: (error: unknown) => boolean;
|
||||
bootstrapUserId: string;
|
||||
defaultSystemConfigId: string;
|
||||
clearAuthEnabledCache: () => void;
|
||||
};
|
||||
|
||||
class HttpError extends Error {
|
||||
@@ -86,6 +87,7 @@ export const registerCoreRoutes = (deps: RegisterCoreRoutesDeps) => {
|
||||
isMissingRefreshTokenTableError,
|
||||
bootstrapUserId,
|
||||
defaultSystemConfigId,
|
||||
clearAuthEnabledCache,
|
||||
} = deps;
|
||||
const getUserTrashCollectionId = (userId: string): string => `trash:${userId}`;
|
||||
|
||||
@@ -713,6 +715,7 @@ export const registerCoreRoutes = (deps: RegisterCoreRoutesDeps) => {
|
||||
registrationEnabled: systemConfig.registrationEnabled,
|
||||
},
|
||||
});
|
||||
clearAuthEnabledCache();
|
||||
|
||||
const bootstrapUser = await prisma.user.findUnique({
|
||||
where: { id: bootstrapUserId },
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
import type { NextFunction, Request, Response } from "express";
|
||||
import jwt from "jsonwebtoken";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { config } from "../config";
|
||||
import { createAuthMiddleware } from "./auth";
|
||||
|
||||
const createRequest = (overrides?: Partial<Request>): Request =>
|
||||
({
|
||||
method: "GET",
|
||||
originalUrl: "/drawings",
|
||||
url: "/drawings",
|
||||
headers: {},
|
||||
...overrides,
|
||||
}) as Request;
|
||||
|
||||
const createResponse = (): Response =>
|
||||
({
|
||||
status: vi.fn().mockReturnThis(),
|
||||
json: vi.fn().mockReturnThis(),
|
||||
}) as unknown as Response;
|
||||
|
||||
const createDeps = () => {
|
||||
const prisma = {
|
||||
user: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
} as any;
|
||||
|
||||
const authModeService = {
|
||||
getAuthEnabled: vi.fn(),
|
||||
getBootstrapActingUser: vi.fn(),
|
||||
} as any;
|
||||
|
||||
return { prisma, authModeService };
|
||||
};
|
||||
|
||||
const makeAccessToken = (payload?: { userId?: string; email?: string; impersonatorId?: string }) =>
|
||||
jwt.sign(
|
||||
{
|
||||
userId: payload?.userId ?? "user-1",
|
||||
email: payload?.email ?? "user-1@test.local",
|
||||
type: "access",
|
||||
impersonatorId: payload?.impersonatorId,
|
||||
},
|
||||
config.jwtSecret
|
||||
);
|
||||
|
||||
const makeRefreshToken = () =>
|
||||
jwt.sign(
|
||||
{
|
||||
userId: "user-1",
|
||||
email: "user-1@test.local",
|
||||
type: "refresh",
|
||||
},
|
||||
config.jwtSecret
|
||||
);
|
||||
|
||||
describe("auth middleware", () => {
|
||||
it("treats requests as bootstrap user when auth is disabled", async () => {
|
||||
const { prisma, authModeService } = createDeps();
|
||||
authModeService.getAuthEnabled.mockResolvedValue(false);
|
||||
authModeService.getBootstrapActingUser.mockResolvedValue({
|
||||
id: "bootstrap-admin",
|
||||
username: null,
|
||||
email: "bootstrap@excalidash.local",
|
||||
name: "Bootstrap Admin",
|
||||
role: "ADMIN",
|
||||
mustResetPassword: true,
|
||||
});
|
||||
const { requireAuth } = createAuthMiddleware({ prisma, authModeService });
|
||||
|
||||
const req = createRequest();
|
||||
const res = createResponse();
|
||||
const next = vi.fn() as NextFunction;
|
||||
|
||||
await requireAuth(req, res, next);
|
||||
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
expect(req.user).toMatchObject({
|
||||
id: "bootstrap-admin",
|
||||
role: "ADMIN",
|
||||
});
|
||||
expect(prisma.user.findUnique).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 401 when token is missing and auth is enabled", async () => {
|
||||
const { prisma, authModeService } = createDeps();
|
||||
authModeService.getAuthEnabled.mockResolvedValue(true);
|
||||
const { requireAuth } = createAuthMiddleware({ prisma, authModeService });
|
||||
|
||||
const req = createRequest();
|
||||
const res = createResponse();
|
||||
const next = vi.fn() as NextFunction;
|
||||
|
||||
await requireAuth(req, res, next);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(401);
|
||||
expect(res.json).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ message: "Authentication token required" })
|
||||
);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects non-access JWT payloads", async () => {
|
||||
const { prisma, authModeService } = createDeps();
|
||||
authModeService.getAuthEnabled.mockResolvedValue(true);
|
||||
const { requireAuth } = createAuthMiddleware({ prisma, authModeService });
|
||||
|
||||
const req = createRequest({
|
||||
headers: {
|
||||
authorization: `Bearer ${makeRefreshToken()}`,
|
||||
},
|
||||
});
|
||||
const res = createResponse();
|
||||
const next = vi.fn() as NextFunction;
|
||||
|
||||
await requireAuth(req, res, next);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(401);
|
||||
expect(res.json).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ message: "Invalid or expired token" })
|
||||
);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("attaches active user for valid access token", async () => {
|
||||
const { prisma, authModeService } = createDeps();
|
||||
authModeService.getAuthEnabled.mockResolvedValue(true);
|
||||
prisma.user.findUnique.mockResolvedValue({
|
||||
id: "user-1",
|
||||
username: "user1",
|
||||
email: "user-1@test.local",
|
||||
name: "User One",
|
||||
role: "USER",
|
||||
mustResetPassword: false,
|
||||
isActive: true,
|
||||
});
|
||||
const { requireAuth } = createAuthMiddleware({ prisma, authModeService });
|
||||
|
||||
const req = createRequest({
|
||||
headers: {
|
||||
authorization: `Bearer ${makeAccessToken({ impersonatorId: "admin-1" })}`,
|
||||
},
|
||||
});
|
||||
const res = createResponse();
|
||||
const next = vi.fn() as NextFunction;
|
||||
|
||||
await requireAuth(req, res, next);
|
||||
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
expect(req.user).toMatchObject({
|
||||
id: "user-1",
|
||||
email: "user-1@test.local",
|
||||
impersonatorId: "admin-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("blocks non-auth routes when password reset is required", async () => {
|
||||
const { prisma, authModeService } = createDeps();
|
||||
authModeService.getAuthEnabled.mockResolvedValue(true);
|
||||
prisma.user.findUnique.mockResolvedValue({
|
||||
id: "user-1",
|
||||
username: "user1",
|
||||
email: "user-1@test.local",
|
||||
name: "User One",
|
||||
role: "USER",
|
||||
mustResetPassword: true,
|
||||
isActive: true,
|
||||
});
|
||||
const { requireAuth } = createAuthMiddleware({ prisma, authModeService });
|
||||
|
||||
const req = createRequest({
|
||||
method: "GET",
|
||||
originalUrl: "/drawings",
|
||||
headers: {
|
||||
authorization: `Bearer ${makeAccessToken()}`,
|
||||
},
|
||||
});
|
||||
const res = createResponse();
|
||||
const next = vi.fn() as NextFunction;
|
||||
|
||||
await requireAuth(req, res, next);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(403);
|
||||
expect(res.json).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ code: "MUST_RESET_PASSWORD" })
|
||||
);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("allows /api/auth/me when password reset is required", async () => {
|
||||
const { prisma, authModeService } = createDeps();
|
||||
authModeService.getAuthEnabled.mockResolvedValue(true);
|
||||
prisma.user.findUnique.mockResolvedValue({
|
||||
id: "user-1",
|
||||
username: "user1",
|
||||
email: "user-1@test.local",
|
||||
name: "User One",
|
||||
role: "USER",
|
||||
mustResetPassword: true,
|
||||
isActive: true,
|
||||
});
|
||||
const { requireAuth } = createAuthMiddleware({ prisma, authModeService });
|
||||
|
||||
const req = createRequest({
|
||||
method: "GET",
|
||||
originalUrl: "/api/auth/me?include=roles",
|
||||
headers: {
|
||||
authorization: `Bearer ${makeAccessToken()}`,
|
||||
},
|
||||
});
|
||||
const res = createResponse();
|
||||
const next = vi.fn() as NextFunction;
|
||||
|
||||
await requireAuth(req, res, next);
|
||||
|
||||
expect(next).toHaveBeenCalledTimes(1);
|
||||
expect(res.status).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { Request } from "express";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
CSRF_CLIENT_COOKIE_NAME,
|
||||
getCsrfClientCookieValue,
|
||||
getCsrfValidationClientIds,
|
||||
getLegacyClientId,
|
||||
parseCookies,
|
||||
} from "./csrfClient";
|
||||
|
||||
const makeRequest = (overrides?: Partial<Request>): Request =>
|
||||
({
|
||||
headers: {
|
||||
cookie: "",
|
||||
"user-agent": "UnitTestAgent/1.0",
|
||||
},
|
||||
ip: "203.0.113.10",
|
||||
connection: { remoteAddress: "198.51.100.8" },
|
||||
...overrides,
|
||||
}) as unknown as Request;
|
||||
|
||||
describe("csrfClient helpers", () => {
|
||||
it("parses cookies and tolerates bad encoding", () => {
|
||||
const parsed = parseCookies("a=1; b=hello%20world; c=%E0%A4%A");
|
||||
expect(parsed).toEqual({
|
||||
a: "1",
|
||||
b: "hello world",
|
||||
c: "%E0%A4%A",
|
||||
});
|
||||
});
|
||||
|
||||
it("reads only valid csrf cookie values", () => {
|
||||
const validReq = makeRequest({
|
||||
headers: {
|
||||
cookie: `${CSRF_CLIENT_COOKIE_NAME}=abcDEF1234567890_-`,
|
||||
},
|
||||
});
|
||||
expect(getCsrfClientCookieValue(validReq)).toBe("abcDEF1234567890_-");
|
||||
|
||||
const invalidReq = makeRequest({
|
||||
headers: {
|
||||
cookie: `${CSRF_CLIENT_COOKIE_NAME}=bad!`,
|
||||
},
|
||||
});
|
||||
expect(getCsrfClientCookieValue(invalidReq)).toBeNull();
|
||||
});
|
||||
|
||||
it("builds legacy client id from IP + user agent and truncates", () => {
|
||||
const longAgent = "x".repeat(600);
|
||||
const req = makeRequest({
|
||||
headers: {
|
||||
"user-agent": longAgent,
|
||||
},
|
||||
});
|
||||
const id = getLegacyClientId(req);
|
||||
expect(id.startsWith("203.0.113.10:")).toBe(true);
|
||||
expect(id.length).toBeLessThanOrEqual(256);
|
||||
});
|
||||
|
||||
it("returns validation candidates with cookie id first when present", () => {
|
||||
const req = makeRequest({
|
||||
headers: {
|
||||
cookie: `${CSRF_CLIENT_COOKIE_NAME}=cookieToken123456`,
|
||||
"user-agent": "Agent",
|
||||
},
|
||||
ip: "10.0.0.1",
|
||||
});
|
||||
|
||||
const candidates = getCsrfValidationClientIds(req);
|
||||
expect(candidates[0]).toBe("cookie:cookieToken123456");
|
||||
expect(candidates[1]).toContain("10.0.0.1:Agent");
|
||||
expect(new Set(candidates).size).toBe(candidates.length);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createDrawingsCacheStore } from "./drawingsCache";
|
||||
|
||||
describe("drawings cache store", () => {
|
||||
let now = 0;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.spyOn(Date, "now").mockImplementation(() => now);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("builds deterministic cache keys", () => {
|
||||
const { buildDrawingsCacheKey } = createDrawingsCacheStore(5000);
|
||||
const keyA = buildDrawingsCacheKey({
|
||||
userId: "u1",
|
||||
searchTerm: "roadmap",
|
||||
collectionFilter: "default",
|
||||
includeData: false,
|
||||
sortField: "updatedAt",
|
||||
sortDirection: "desc",
|
||||
});
|
||||
const keyB = buildDrawingsCacheKey({
|
||||
userId: "u1",
|
||||
searchTerm: "roadmap",
|
||||
collectionFilter: "default",
|
||||
includeData: false,
|
||||
sortField: "updatedAt",
|
||||
sortDirection: "desc",
|
||||
});
|
||||
const keyC = buildDrawingsCacheKey({
|
||||
userId: "u1",
|
||||
searchTerm: "roadmap",
|
||||
collectionFilter: "default",
|
||||
includeData: true,
|
||||
sortField: "updatedAt",
|
||||
sortDirection: "desc",
|
||||
});
|
||||
|
||||
expect(keyA).toBe(keyB);
|
||||
expect(keyA).not.toBe(keyC);
|
||||
});
|
||||
|
||||
it("caches payloads and expires by TTL", () => {
|
||||
const { cacheDrawingsResponse, getCachedDrawingsBody } = createDrawingsCacheStore(1000);
|
||||
const key = "drawings:key:1";
|
||||
const payload = { drawings: [{ id: "d1" }], totalCount: 1 };
|
||||
|
||||
const body = cacheDrawingsResponse(key, payload);
|
||||
expect(body.toString("utf8")).toContain("\"totalCount\":1");
|
||||
|
||||
now = 800;
|
||||
expect(getCachedDrawingsBody(key)?.toString("utf8")).toContain("\"d1\"");
|
||||
|
||||
now = 1200;
|
||||
expect(getCachedDrawingsBody(key)).toBeNull();
|
||||
});
|
||||
|
||||
it("supports manual invalidation", () => {
|
||||
const { cacheDrawingsResponse, getCachedDrawingsBody, invalidateDrawingsCache } =
|
||||
createDrawingsCacheStore(10_000);
|
||||
const key = "drawings:key:2";
|
||||
|
||||
cacheDrawingsResponse(key, { drawings: [], totalCount: 0 });
|
||||
expect(getCachedDrawingsBody(key)).not.toBeNull();
|
||||
|
||||
invalidateDrawingsCache();
|
||||
expect(getCachedDrawingsBody(key)).toBeNull();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user