Files
canina/backend/src/common/revalidation/revalidation.service.ts
T
2026-10-26 15:12:10 +00:00

175 lines
5.0 KiB
TypeScript

import { Injectable, Logger } from "@nestjs/common";
@Injectable()
export class RevalidationService {
private readonly logger = new Logger(RevalidationService.name);
private get frontendUrl(): string {
const raw =
process.env.FRONTEND_INTERNAL_URL ||
process.env.FRONTEND_URL ||
process.env.NEXT_PUBLIC_SITE_URL ||
(process.env.NODE_ENV === "production"
? "http://frontend_prod:3000"
: "http://localhost:3000");
return raw.replace(/\/+$/, "");
}
private get secret(): string {
const secret = process.env.REVALIDATION_SECRET;
if (!secret) {
if (process.env.NODE_ENV === "production") {
throw new Error(
"REVALIDATION_SECRET is required in production environment.",
);
}
this.logger.warn(
"REVALIDATION_SECRET is not defined in environment variables.",
);
return "";
}
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`;
const res = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-revalidate-secret": this.secret,
},
body: JSON.stringify({ tag, secret: this.secret }),
});
if (!res.ok) {
this.logger.warn(
`Failed to revalidate tag [${tag}] on frontend: ${res.status} ${res.statusText}`,
);
return false;
}
this.logger.log(`Successfully revalidated cache tag [${tag}]`);
return true;
} catch (err: any) {
this.logger.debug(
`Revalidation tag request skipped or frontend offline: ${err?.message}`,
);
return false;
}
}
async revalidatePath(path: string): Promise<boolean> {
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({ path, secret: this.secret }),
});
if (!res.ok) {
this.logger.warn(
`Failed to revalidate path [${path}] on frontend: ${res.status} ${res.statusText}`,
);
return false;
}
this.logger.log(`Successfully revalidated cache path [${path}]`);
return true;
} catch (err: any) {
this.logger.debug(
`Revalidation path request skipped or frontend offline: ${err?.message}`,
);
return false;
}
}
async revalidateProduct(slug?: string, artNo?: string): Promise<void> {
const tasks: Promise<boolean>[] = [
this.revalidateTag("products"),
this.revalidateTag("home-data"),
this.revalidatePath("/shop"),
this.revalidatePath("/"),
];
if (slug) {
tasks.push(this.revalidateTag(`product-${slug}`));
tasks.push(this.revalidatePath(`/shop/${slug}`));
}
if (artNo && artNo !== slug) {
tasks.push(this.revalidateTag(`product-${artNo}`));
tasks.push(this.revalidatePath(`/shop/${artNo}`));
}
await Promise.allSettled(tasks);
}
async revalidateBlog(slug?: string): Promise<boolean> {
const tasks: Promise<boolean>[] = [
this.revalidateTag("blogs"),
this.revalidateTag("home-data"),
this.revalidatePath("/blog"),
this.revalidatePath("/sitemap.xml"),
this.revalidatePath("/"),
];
if (slug) {
tasks.push(this.revalidateTag(`blog-${slug}`));
tasks.push(this.revalidatePath(`/blog/${slug}`));
}
try {
const results = await Promise.allSettled(tasks);
return (
results.length > 0 &&
results.every(
(result) => result.status === "fulfilled" && result.value === true,
)
);
} catch (err: any) {
this.logger.debug(`Revalidation blog skipped or failed: ${err?.message}`);
return false;
}
}
async revalidateSettings(): Promise<void> {
await Promise.allSettled([
this.revalidateTag("settings"),
this.revalidateTag("home-data"),
this.revalidateTag("seo-config"),
this.revalidatePath("/"),
]);
}
}