fix(cache): revalidate storefront after admin mutations
Deploy Canina / deploy (push) Successful in 2m35s
Deploy Canina / deploy (push) Successful in 2m35s
This commit is contained in:
1 parent
2e9a0e30c1
commit
ff6f04fe46
7 files changed
+205
-49
No files matched your search
@@ -0,0 +1,61 @@
|
||||
import { CallHandler, ExecutionContext } from "@nestjs/common";
|
||||
import { of, lastValueFrom } from "rxjs";
|
||||
import { AdminRevalidationInterceptor } from "./admin-revalidation.interceptor";
|
||||
import { RevalidationService } from "./revalidation.service";
|
||||
|
||||
describe("AdminRevalidationInterceptor", () => {
|
||||
const revalidation = { revalidate: jest.fn().mockResolvedValue(true) } as unknown as RevalidationService;
|
||||
const interceptor = new AdminRevalidationInterceptor(revalidation);
|
||||
const next = { handle: () => of({ ok: true }) } as CallHandler;
|
||||
|
||||
beforeEach(() => jest.clearAllMocks());
|
||||
|
||||
function context(method: string, url: string): ExecutionContext {
|
||||
return { switchToHttp: () => ({ getRequest: () => ({ method, originalUrl: url }) }) } as unknown as ExecutionContext;
|
||||
}
|
||||
|
||||
it("invalidates blog list and detail after an admin blog mutation", async () => {
|
||||
await lastValueFrom(interceptor.intercept(context("PUT", "/api/admin/blogs/blog-1"), next));
|
||||
expect(revalidation.revalidate).toHaveBeenCalledWith(
|
||||
expect.arrayContaining(["blogs", "blog-categories", "blog-tags", "home-data"]),
|
||||
expect.arrayContaining(["/", "/blog"]),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["/api/admin/products/p1", "products"],
|
||||
["/api/admin/categories/c1", "categories"],
|
||||
["/api/admin/wiki/glucosamine", "wiki"],
|
||||
["/api/admin/settings", "settings"],
|
||||
["/api/admin/cms/hero-banners/b1", "banners"],
|
||||
["/api/admin/cms/vet-testimonials/t1", "testimonials"],
|
||||
["/api/admin/reviews/r1", "products"],
|
||||
["/api/admin/media/m1", "products"],
|
||||
])("maps %s mutations to %s cache invalidation", async (url, expectedTag) => {
|
||||
await lastValueFrom(interceptor.intercept(context("DELETE", url), next));
|
||||
expect(revalidation.revalidate).toHaveBeenCalledWith(expect.arrayContaining([expectedTag]), expect.any(Array));
|
||||
});
|
||||
|
||||
it("does not invalidate cache for reads or internal-only admin CRUD", async () => {
|
||||
await lastValueFrom(interceptor.intercept(context("GET", "/api/admin/blogs"), next));
|
||||
await lastValueFrom(interceptor.intercept(context("PUT", "/api/admin/users/u1"), next));
|
||||
expect(revalidation.revalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["/api/banners/banner-1", "banners"],
|
||||
["/api/menu/menu-1", "menu"],
|
||||
["/api/videos/video-1", "videos"],
|
||||
["/api/testimonials/testimonial-1", "testimonials"],
|
||||
["/api/faq/faq-1", "faq"],
|
||||
["/api/ingredients/ingredient-1", "ingredients"],
|
||||
["/api/doctors/doctor-1", "doctors"],
|
||||
["/api/settings/seo", "seo-config"],
|
||||
["/api/settings/ui-texts/HERO_TITLE", "ui-texts"],
|
||||
["/api/contact/info", "settings"],
|
||||
["/api/smart-advisor/rules/rule-1", "smart-advisor"],
|
||||
])("maps storefront mutation %s to %s cache invalidation", async (url, expectedTag) => {
|
||||
await lastValueFrom(interceptor.intercept(context("PATCH", url), next));
|
||||
expect(revalidation.revalidate).toHaveBeenCalledWith(expect.arrayContaining([expectedTag]), expect.any(Array));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
|
||||
import { Observable, tap } from "rxjs";
|
||||
import { RevalidationService } from "./revalidation.service";
|
||||
|
||||
type Target = { tags: string[]; paths: string[] };
|
||||
|
||||
const TARGETS: Array<{ pattern: RegExp; target: Target }> = [
|
||||
{ pattern: /^\/api\/banners(?:\/|$)/, target: { tags: ["banners", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/menu(?:\/|$)/, target: { tags: ["menu", "settings"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/videos(?:\/|$)/, target: { tags: ["videos", "home-data"], paths: ["/", "/videos"] } },
|
||||
{ pattern: /^\/api\/testimonials(?:\/|$)/, target: { tags: ["testimonials", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/faq(?:\/|$)/, target: { tags: ["faq"], paths: ["/faq"] } },
|
||||
{ pattern: /^\/api\/ingredients(?:\/|$)/, target: { tags: ["ingredients", "products", "wiki"], paths: ["/shop", "/wiki"] } },
|
||||
{ pattern: /^\/api\/doctors(?:\/|$)/, target: { tags: ["doctors", "settings"], paths: ["/contact"] } },
|
||||
{ pattern: /^\/api\/settings\/seo(?:\/|$)/, target: { tags: ["seo-config", "settings"], paths: ["/", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/settings\/(?:ui-texts|system|financial)(?:\/|$)/, target: { tags: ["ui-texts", "settings", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/contact\/info(?:\/|$)/, target: { tags: ["settings"], paths: ["/contact", "/"] } },
|
||||
{ pattern: /^\/api\/smart-advisor\/rules(?:\/|$)/, target: { tags: ["smart-advisor", "products"], paths: ["/smart-advisor"] } },
|
||||
{ pattern: /^\/api\/admin\/blogs(?:\/|$)/, target: { tags: ["blogs", "blog-categories", "blog-tags", "home-data"], paths: ["/", "/blog", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/admin\/categories(?:\/|$)/, target: { tags: ["products", "categories", "home-data"], paths: ["/", "/shop", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/admin\/wiki(?:\/|$)/, target: { tags: ["wiki", "scientific-terms"], paths: ["/wiki", "/sitemap.xml"] } },
|
||||
{ pattern: /^\/api\/admin\/(?:settings|pricing)(?:\/|$)/, target: { tags: ["settings", "ui-texts", "seo-config", "products", "home-data"], paths: ["/", "/shop"] } },
|
||||
{ pattern: /^\/api\/admin\/cms\/hero-banners(?:\/|$)/, target: { tags: ["banners", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/admin\/cms\/vet-testimonials(?:\/|$)/, target: { tags: ["testimonials", "home-data"], paths: ["/"] } },
|
||||
{ pattern: /^\/api\/admin\/reviews(?:\/|$)/, target: { tags: ["products", "home-data"], paths: ["/", "/shop"] } },
|
||||
{ pattern: /^\/api\/admin\/media(?:\/|$)/, target: { tags: ["products", "blogs", "wiki", "home-data"], paths: ["/", "/shop", "/blog", "/wiki"] } },
|
||||
{ pattern: /^\/api\/admin\/products(?:\/|$)/, target: { tags: ["products", "home-data"], paths: ["/", "/shop", "/sitemap.xml"] } },
|
||||
];
|
||||
|
||||
@Injectable()
|
||||
export class AdminRevalidationInterceptor implements NestInterceptor {
|
||||
constructor(private readonly revalidation: RevalidationService) {}
|
||||
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||
const request = context.switchToHttp().getRequest<{ method?: string; originalUrl?: string; url?: string }>();
|
||||
const method = (request.method || "GET").toUpperCase();
|
||||
const url = (request.originalUrl || request.url || "").split("?")[0];
|
||||
const target = method === "GET" || method === "HEAD" || method === "OPTIONS"
|
||||
? undefined
|
||||
: TARGETS.find((entry) => entry.pattern.test(url))?.target;
|
||||
|
||||
return next.handle().pipe(
|
||||
tap(() => {
|
||||
if (target) void this.revalidation.revalidate(target.tags, target.paths);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { Global, Module } from "@nestjs/common";
|
||||
import { APP_INTERCEPTOR } from "@nestjs/core";
|
||||
import { AdminRevalidationInterceptor } from "./admin-revalidation.interceptor";
|
||||
import { RevalidationService } from "./revalidation.service";
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [RevalidationService],
|
||||
providers: [RevalidationService, { provide: APP_INTERCEPTOR, useClass: AdminRevalidationInterceptor }],
|
||||
exports: [RevalidationService],
|
||||
})
|
||||
export class RevalidationModule {}
|
||||
@@ -110,4 +110,22 @@ describe("RevalidationService", () => {
|
||||
expect(pathSpy).toHaveBeenCalledWith("/shop/ART-100");
|
||||
});
|
||||
});
|
||||
|
||||
describe("revalidate batch", () => {
|
||||
it("should send deduplicated tags and paths in one request", async () => {
|
||||
const mockFetch = jest.spyOn(global, "fetch" as any).mockResolvedValue({ ok: true, status: 200 } as any);
|
||||
|
||||
const result = await service.revalidate(["blogs", "blogs"], ["/blog", "/blog"]);
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
"http://frontend_mock:8080/api/revalidate",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
body: JSON.stringify({ tags: ["blogs"], paths: ["/blog"] }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -31,6 +31,32 @@ export class RevalidationService {
|
||||
return secret;
|
||||
}
|
||||
|
||||
async revalidate(tags: string[] = [], paths: string[] = []): Promise<boolean> {
|
||||
const cleanTags = [...new Set(tags.filter(Boolean))];
|
||||
const cleanPaths = [...new Set(paths.filter((path) => path.startsWith("/")))];
|
||||
if (!cleanTags.length && !cleanPaths.length) return true;
|
||||
|
||||
try {
|
||||
const url = `${this.frontendUrl}/api/revalidate`;
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-revalidate-secret": this.secret,
|
||||
},
|
||||
body: JSON.stringify({ tags: cleanTags, paths: cleanPaths }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
this.logger.warn(`Failed to revalidate cache batch: ${res.status} ${res.statusText}`);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (err: any) {
|
||||
this.logger.debug(`Batch revalidation skipped or frontend offline: ${err?.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async revalidateTag(tag: string): Promise<boolean> {
|
||||
try {
|
||||
const url = `${this.frontendUrl}/api/revalidate`;
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
import { revalidatePath, revalidateTag } from "next/cache";
|
||||
import { POST } from "./route";
|
||||
|
||||
vi.mock("next/cache", () => ({ revalidatePath: vi.fn(), revalidateTag: vi.fn() }));
|
||||
|
||||
describe("revalidation route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.REVALIDATION_SECRET = "test-secret";
|
||||
});
|
||||
|
||||
it("revalidates deduplicated tag and path batches", async () => {
|
||||
const request = new NextRequest("http://localhost/api/revalidate", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", "x-revalidate-secret": "test-secret" },
|
||||
body: JSON.stringify({ tags: ["blogs", "blogs"], paths: ["/blog", "/blog"] }),
|
||||
});
|
||||
|
||||
const response = await POST(request);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(revalidateTag).toHaveBeenCalledTimes(1);
|
||||
expect(revalidateTag).toHaveBeenCalledWith("blogs", "default");
|
||||
expect(revalidatePath).toHaveBeenCalledTimes(1);
|
||||
expect(revalidatePath).toHaveBeenCalledWith("/blog", "page");
|
||||
});
|
||||
});
|
||||
@@ -12,69 +12,41 @@ export async function POST(request: NextRequest) {
|
||||
async function handleRevalidate(request: NextRequest) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
let secret = searchParams.get('secret') || request.headers.get('x-revalidate-secret');
|
||||
let tag = searchParams.get('tag');
|
||||
let path = searchParams.get('path');
|
||||
let tags: unknown[] = searchParams.getAll('tag');
|
||||
let paths: unknown[] = searchParams.getAll('path');
|
||||
|
||||
// Check auth header if bearer token provided
|
||||
const authHeader = request.headers.get('authorization');
|
||||
if (authHeader && authHeader.startsWith('Bearer ')) {
|
||||
secret = authHeader.substring(7);
|
||||
}
|
||||
if (authHeader?.startsWith('Bearer ')) secret = authHeader.substring(7);
|
||||
|
||||
if (request.method === 'POST') {
|
||||
try {
|
||||
const body = await request.json().catch(() => ({}));
|
||||
if (body && typeof body === 'object') {
|
||||
if (body.secret) secret = body.secret;
|
||||
if (body.tag) tag = body.tag;
|
||||
if (body.path) path = body.path;
|
||||
}
|
||||
} catch {
|
||||
// Ignore body read error
|
||||
const body = await request.json().catch(() => ({}));
|
||||
if (body && typeof body === 'object') {
|
||||
if (body.secret) secret = body.secret;
|
||||
if (body.tag) tags = [body.tag];
|
||||
if (Array.isArray(body.tags)) tags = body.tags;
|
||||
if (body.path) paths = [body.path];
|
||||
if (Array.isArray(body.paths)) paths = body.paths;
|
||||
}
|
||||
}
|
||||
|
||||
const expectedSecret = process.env.REVALIDATION_SECRET;
|
||||
if (!expectedSecret) {
|
||||
return NextResponse.json(
|
||||
{ success: false, message: 'Revalidation service is not configured' },
|
||||
{ status: 503 }
|
||||
);
|
||||
return NextResponse.json({ success: false, message: 'Revalidation service is not configured' }, { status: 503 });
|
||||
}
|
||||
|
||||
if (!secret || secret !== expectedSecret) {
|
||||
return NextResponse.json(
|
||||
{ success: false, message: 'Invalid revalidation secret token' },
|
||||
{ status: 401 }
|
||||
);
|
||||
return NextResponse.json({ success: false, message: 'Invalid revalidation secret token' }, { status: 401 });
|
||||
}
|
||||
|
||||
if (!tag && !path) {
|
||||
return NextResponse.json(
|
||||
{ success: false, message: 'Missing tag or path parameter for cache revalidation' },
|
||||
{ status: 400 }
|
||||
);
|
||||
const cleanTags = [...new Set(tags.filter((value): value is string => typeof value === 'string' && value.length > 0))];
|
||||
const cleanPaths = [...new Set(paths.filter((value): value is string => typeof value === 'string' && value.startsWith('/')))];
|
||||
if (!cleanTags.length && !cleanPaths.length) {
|
||||
return NextResponse.json({ success: false, message: 'Missing tag or path parameter for cache revalidation' }, { status: 400 });
|
||||
}
|
||||
|
||||
const revalidated: { tag?: string; path?: string } = {};
|
||||
|
||||
if (tag) {
|
||||
revalidateTag(tag, 'default');
|
||||
revalidated.tag = tag;
|
||||
for (const tag of cleanTags) revalidateTag(tag, 'default');
|
||||
for (const path of cleanPaths) {
|
||||
try { revalidatePath(path, 'page'); } catch { revalidatePath(path); }
|
||||
}
|
||||
|
||||
if (path) {
|
||||
try {
|
||||
revalidatePath(path, 'page');
|
||||
} catch {
|
||||
revalidatePath(path);
|
||||
}
|
||||
revalidated.path = path;
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
revalidated: true,
|
||||
...revalidated,
|
||||
now: Date.now(),
|
||||
});
|
||||
return NextResponse.json({ revalidated: true, tags: cleanTags, paths: cleanPaths, now: Date.now() });
|
||||
}
|
||||
Reference in new issue
Block a user