feat(perf): implement comprehensive Core Web Vitals, ISR caching, and media optimizations
Deploy Canina / deploy (push) Successful in 1m48s

This commit is contained in:
parsa aghaei committed 2026-08-24 17:23:43 +03:30
1 parent 2a31a9f8e4
commit fe6a900665
42 files changed
+12941 -10561

No files matched your search

+25 -3
View File
@@ -12,6 +12,7 @@ import { CreateUserDto, UpdateUserDto } from './dto/user.dto';
import { ProductDto } from './dto/product.dto';
import { normalizeMobile } from '../common/utils/phone.utils';
import { CANONICAL_ALIASES } from '../settings/settings.service';
import { RevalidationService } from '../common/revalidation/revalidation.service';
export class PaginationQuery {
page?: number | string;
@@ -51,6 +52,7 @@ export class AdminService {
constructor(
private prisma: PrismaService,
private redisService: RedisService,
private revalidationService: RevalidationService,
) {}
async getDashboardStats() {
@@ -456,6 +458,10 @@ export class AdminService {
});
}
await this.revalidationService.revalidateProduct(
product.slug,
product.artNo,
);
return product;
}
@@ -516,11 +522,15 @@ export class AdminService {
metaDescription: data.metaDescription,
keywords: data.keywords,
canonicalUrl: data.canonicalUrl,
stockStatus: data.stockStatus !== undefined ? data.stockStatus : undefined,
stockStatus:
data.stockStatus !== undefined ? data.stockStatus : undefined,
noIndex: data.noIndex !== undefined ? data.noIndex : undefined,
noFollow: data.noFollow !== undefined ? data.noFollow : undefined,
ogImage: data.ogImage !== undefined ? data.ogImage : undefined,
featuredImageAlt: data.featuredImageAlt !== undefined ? data.featuredImageAlt : undefined,
featuredImageAlt:
data.featuredImageAlt !== undefined
? data.featuredImageAlt
: undefined,
slug: data.slug || data.artNo,
},
});
@@ -539,13 +549,25 @@ export class AdminService {
}
}
await this.revalidationService.revalidateProduct(
product.slug,
product.artNo,
);
return product;
}
async deleteProduct(id: string) {
return this.prisma.product.delete({
const existing = await this.prisma.product.findUnique({ where: { id } });
const res = await this.prisma.product.delete({
where: { id },
});
if (existing) {
await this.revalidationService.revalidateProduct(
existing.slug,
existing.artNo,
);
}
return res;
}
async getOrders(query: PaginationQuery = {}) {
+7 -5
View File
@@ -37,7 +37,12 @@ export class BlogsController {
@ApiQuery({ name: 'status', required: false })
@ApiQuery({ name: 'categoryId', required: false })
async getBlogs(
@Query() query: PaginationDto & { status?: string; categoryId?: string; tagId?: string },
@Query()
query: PaginationDto & {
status?: string;
categoryId?: string;
tagId?: string;
},
) {
return this.blogsService.getBlogs(query);
}
@@ -120,10 +125,7 @@ export class BlogsController {
@Put(':id')
@ApiOperation({ summary: 'ویرایش مقاله' })
async updateBlog(
@Param('id') id: string,
@Body() body: any,
) {
async updateBlog(@Param('id') id: string, @Body() body: any) {
const data = await this.blogsService.updateBlog(id, body);
return { success: true, data };
}
+82 -18
View File
@@ -2,12 +2,22 @@ import { Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { PaginationDto } from '../common/dto/pagination.dto';
import { RevalidationService } from '../common/revalidation/revalidation.service';
@Injectable()
export class BlogsService {
constructor(private prisma: PrismaService) {}
constructor(
private prisma: PrismaService,
private revalidationService: RevalidationService,
) {}
async getBlogs(query: PaginationDto & { status?: string; categoryId?: string; tagId?: string }) {
async getBlogs(
query: PaginationDto & {
status?: string;
categoryId?: string;
tagId?: string;
},
) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;
const skip = (page - 1) * limit;
@@ -37,7 +47,9 @@ export class BlogsService {
take: limit,
orderBy: { createdAt: 'desc' },
include: {
author: { select: { id: true, firstName: true, lastName: true, email: true } },
author: {
select: { id: true, firstName: true, lastName: true, email: true },
},
category: { select: { id: true, name: true, slug: true } },
tags: { select: { id: true, name: true, slug: true } },
_count: { select: { comments: true } },
@@ -87,7 +99,10 @@ export class BlogsService {
for (const tName of tagNames) {
const trimmed = String(tName).trim();
if (trimmed) {
const slug = trimmed.toLowerCase().replace(/\s+/g, '-').replace(/[^\w\u0600-\u06FF-]+/g, '');
const slug = trimmed
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^\w\u0600-\u06FF-]+/g, '');
tagConnectOrCreate.push({
where: { name: trimmed },
create: { name: trimmed, slug: slug || `tag-${Date.now()}` },
@@ -101,13 +116,19 @@ export class BlogsService {
const createPayload: Prisma.BlogCreateInput = {
...rest,
readingTime: readingTime ? Number(readingTime) : 3,
publishedAt: publishedAt ? new Date(publishedAt) : (rest.status === 'PUBLISHED' ? new Date() : null),
publishedAt: publishedAt
? new Date(publishedAt)
: rest.status === 'PUBLISHED'
? new Date()
: null,
author: { connect: { id: targetAuthorId } },
...(categoryId ? { category: { connect: { id: categoryId } } } : {}),
...(tagConnectOrCreate.length > 0 ? { tags: { connectOrCreate: tagConnectOrCreate } } : {}),
...(tagConnectOrCreate.length > 0
? { tags: { connectOrCreate: tagConnectOrCreate } }
: {}),
};
return this.prisma.blog.create({
const created = await this.prisma.blog.create({
data: createPayload,
include: {
author: { select: { firstName: true, lastName: true } },
@@ -115,6 +136,9 @@ export class BlogsService {
tags: true,
},
});
await this.revalidationService.revalidateBlog(created.slug);
return created;
}
async updateBlog(id: string, data: any) {
@@ -133,8 +157,12 @@ export class BlogsService {
const updatePayload: Prisma.BlogUpdateInput = {
...rest,
...(readingTime !== undefined ? { readingTime: Number(readingTime) } : {}),
...(publishedAt !== undefined ? { publishedAt: publishedAt ? new Date(publishedAt) : null } : {}),
...(readingTime !== undefined
? { readingTime: Number(readingTime) }
: {}),
...(publishedAt !== undefined
? { publishedAt: publishedAt ? new Date(publishedAt) : null }
: {}),
...(authorId ? { author: { connect: { id: authorId } } } : {}),
...(categoryId !== undefined
? categoryId
@@ -148,7 +176,10 @@ export class BlogsService {
for (const tName of tagNames) {
const trimmed = String(tName).trim();
if (trimmed) {
const slug = trimmed.toLowerCase().replace(/\s+/g, '-').replace(/[^\w\u0600-\u06FF-]+/g, '');
const slug = trimmed
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^\w\u0600-\u06FF-]+/g, '');
tagConnectOrCreate.push({
where: { name: trimmed },
create: { name: trimmed, slug: slug || `tag-${Date.now()}` },
@@ -161,7 +192,7 @@ export class BlogsService {
};
}
return this.prisma.blog.update({
const updated = await this.prisma.blog.update({
where: { id },
data: updatePayload,
include: {
@@ -170,18 +201,29 @@ export class BlogsService {
tags: true,
},
});
await this.revalidationService.revalidateBlog(updated.slug);
return updated;
}
async deleteBlog(id: string) {
const blog = await this.prisma.blog.findUnique({ where: { id } });
if (!blog) throw new NotFoundException('Blog not found');
return this.prisma.blog.delete({ where: { id } });
const res = await this.prisma.blog.delete({ where: { id } });
await this.revalidationService.revalidateBlog(blog.slug);
return res;
}
// Authors (Users who can write)
async getAuthors() {
return this.prisma.user.findMany({
select: { id: true, firstName: true, lastName: true, email: true, role: true },
select: {
id: true,
firstName: true,
lastName: true,
email: true,
role: true,
},
orderBy: { firstName: 'asc' },
});
}
@@ -221,7 +263,12 @@ export class BlogsService {
}
async createBlogTag(data: { name: string; slug?: string }) {
const slug = data.slug || data.name.toLowerCase().replace(/\s+/g, '-').replace(/[^\w\u0600-\u06FF-]+/g, '');
const slug =
data.slug ||
data.name
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^\w\u0600-\u06FF-]+/g, '');
return this.prisma.blogTag.create({
data: { name: data.name, slug: slug || `tag-${Date.now()}` },
});
@@ -267,14 +314,31 @@ export class BlogsService {
}
async updateCommentStatus(id: string, status: 'APPROVED' | 'REJECTED') {
const comment = await this.prisma.blogComment.findUnique({ where: { id } });
const comment = await this.prisma.blogComment.findUnique({
where: { id },
include: { blog: { select: { slug: true } } },
});
if (!comment) throw new NotFoundException('Comment not found');
return this.prisma.blogComment.update({ where: { id }, data: { status } });
const updated = await this.prisma.blogComment.update({
where: { id },
data: { status },
});
if (comment.blog?.slug) {
await this.revalidationService.revalidateBlog(comment.blog.slug);
}
return updated;
}
async deleteComment(id: string) {
const comment = await this.prisma.blogComment.findUnique({ where: { id } });
const comment = await this.prisma.blogComment.findUnique({
where: { id },
include: { blog: { select: { slug: true } } },
});
if (!comment) throw new NotFoundException('Comment not found');
return this.prisma.blogComment.delete({ where: { id } });
const res = await this.prisma.blogComment.delete({ where: { id } });
if (comment.blog?.slug) {
await this.revalidationService.revalidateBlog(comment.blog.slug);
}
return res;
}
}
+10 -3
View File
@@ -198,7 +198,10 @@ export class ProductDto {
@IsArray()
symptoms?: string[];
@ApiPropertyOptional({ description: 'وضعیت موجودی کالا (IN_STOCK, OUT_OF_STOCK, PRE_ORDER, DISCONTINUED)' })
@ApiPropertyOptional({
description:
'وضعیت موجودی کالا (IN_STOCK, OUT_OF_STOCK, PRE_ORDER, DISCONTINUED)',
})
@IsOptional()
@IsString()
stockStatus?: 'IN_STOCK' | 'OUT_OF_STOCK' | 'PRE_ORDER' | 'DISCONTINUED';
@@ -208,12 +211,16 @@ export class ProductDto {
@IsBoolean()
noIndex?: boolean;
@ApiPropertyOptional({ description: 'عدم دنبال کردن لینک‌ها توسط موتورهای جستجو' })
@ApiPropertyOptional({
description: 'عدم دنبال کردن لینک‌ها توسط موتورهای جستجو',
})
@IsOptional()
@IsBoolean()
noFollow?: boolean;
@ApiPropertyOptional({ description: 'تصویر کارت شبکه‌های اجتماعی (og:image)' })
@ApiPropertyOptional({
description: 'تصویر کارت شبکه‌های اجتماعی (og:image)',
})
@IsOptional()
@IsString()
ogImage?: string | null;
+2
View File
@@ -33,11 +33,13 @@ import { ReviewsModule } from './reviews/reviews.module';
import { DoctorsModule } from './doctors/doctors.module';
import { FaqModule } from './faq/faq.module';
import { MenuModule } from './menu/menu.module';
import { RevalidationModule } from './common/revalidation/revalidation.module';
import { Request, Response, NextFunction } from 'express';
@Module({
imports: [
RevalidationModule,
SmsModule,
ContactModule,
PrismaModule,
+25 -12
View File
@@ -29,10 +29,7 @@ export class BlogsService {
const whereClause: Prisma.BlogWhereInput = {
isPublished: true,
status: 'PUBLISHED',
OR: [
{ publishedAt: null },
{ publishedAt: { lte: now } },
],
OR: [{ publishedAt: null }, { publishedAt: { lte: now } }],
};
if (search) {
@@ -67,7 +64,9 @@ export class BlogsService {
where: whereClause,
skip,
take: Number(limit),
orderBy: { [sortBy === 'createdAt' ? 'createdAt' : 'publishedAt']: sortOrder },
orderBy: {
[sortBy === 'createdAt' ? 'createdAt' : 'publishedAt']: sortOrder,
},
include: {
author: {
select: { firstName: true, lastName: true },
@@ -184,7 +183,11 @@ export class BlogsService {
let relatedBlogs: any[] = [];
if (blog.relatedBlogIds && blog.relatedBlogIds.length > 0) {
relatedBlogs = await this.prisma.blog.findMany({
where: { id: { in: blog.relatedBlogIds }, isPublished: true, status: 'PUBLISHED' },
where: {
id: { in: blog.relatedBlogIds },
isPublished: true,
status: 'PUBLISHED',
},
select: {
id: true,
title: true,
@@ -219,10 +222,12 @@ export class BlogsService {
}
// Increment view count asynchronously
await this.prisma.blog.update({
where: { id: blog.id },
data: { viewCount: { increment: 1 } },
}).catch(() => null);
await this.prisma.blog
.update({
where: { id: blog.id },
data: { viewCount: { increment: 1 } },
})
.catch(() => null);
return {
...blog,
@@ -237,7 +242,11 @@ export class BlogsService {
orderBy: { order: 'asc' },
include: {
children: true,
_count: { select: { blogs: { where: { isPublished: true, status: 'PUBLISHED' } } } },
_count: {
select: {
blogs: { where: { isPublished: true, status: 'PUBLISHED' } },
},
},
},
});
}
@@ -246,7 +255,11 @@ export class BlogsService {
return this.prisma.blogTag.findMany({
orderBy: { createdAt: 'desc' },
include: {
_count: { select: { blogs: { where: { isPublished: true, status: 'PUBLISHED' } } } },
_count: {
select: {
blogs: { where: { isPublished: true, status: 'PUBLISHED' } },
},
},
},
});
}
@@ -0,0 +1,9 @@
import { Global, Module } from '@nestjs/common';
import { RevalidationService } from './revalidation.service';
@Global()
@Module({
providers: [RevalidationService],
exports: [RevalidationService],
})
export class RevalidationModule {}
@@ -0,0 +1,123 @@
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_URL ||
process.env.NEXT_PUBLIC_SITE_URL ||
'http://localhost:3000';
return raw.replace(/\/+$/, '');
}
private get secret(): string {
return (
process.env.REVALIDATION_SECRET || 'canina_revalidation_secret_key_2026'
);
}
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<void> {
const tasks: Promise<boolean>[] = [
this.revalidateTag('blogs'),
this.revalidateTag('home-data'),
this.revalidatePath('/blog'),
this.revalidatePath('/'),
];
if (slug) {
tasks.push(this.revalidateTag(`blog-${slug}`));
tasks.push(this.revalidatePath(`/blog/${slug}`));
}
await Promise.allSettled(tasks);
}
async revalidateSettings(): Promise<void> {
await Promise.allSettled([
this.revalidateTag('settings'),
this.revalidateTag('home-data'),
this.revalidateTag('seo-config'),
this.revalidatePath('/'),
]);
}
}
+3
View File
@@ -8,6 +8,7 @@ import { CustomHttpExceptionFilter } from './common/filters/http-exception.filte
import { PrismaExceptionFilter } from './common/filters/prisma-exception.filter';
import { DecimalInterceptor } from './common/interceptors/decimal.interceptor';
import helmet from 'helmet';
import compression from 'compression';
// Ensure BigInt can be serialized to JSON across all NestJS / Express responses
(BigInt.prototype as any).toJSON = function () {
@@ -46,6 +47,8 @@ async function bootstrap() {
...staticUploadOptions,
});
app.use(compression());
app.use(
helmet({
contentSecurityPolicy: false, // Avoid blocking Swagger UI scripts and assets
+11 -2
View File
@@ -2,10 +2,14 @@ import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { GetProductsDto } from './dto/get-products.dto';
import { Prisma } from '@prisma/client';
import { RevalidationService } from '../common/revalidation/revalidation.service';
@Injectable()
export class ProductsService {
constructor(private prisma: PrismaService) {}
constructor(
private prisma: PrismaService,
private revalidationService: RevalidationService,
) {}
async findAll(filters: GetProductsDto, userRole?: string) {
const {
@@ -272,9 +276,14 @@ export class ProductsService {
if (!product) {
throw new NotFoundException(`Product with ID ${id} not found`);
}
return this.prisma.product.update({
const updated = await this.prisma.product.update({
where: { id },
data: { dosageConfig },
});
await this.revalidationService.revalidateProduct(
product.slug,
product.artNo,
);
return updated;
}
}
+21 -1
View File
@@ -7,12 +7,16 @@ import {
import { PrismaService } from '../prisma/prisma.service';
import { CreateReviewDto } from './dto/create-review.dto';
import { UpdateReviewDto } from './dto/update-review.dto';
import { RevalidationService } from '../common/revalidation/revalidation.service';
@Injectable()
export class ReviewsService {
private readonly logger = new Logger(ReviewsService.name);
constructor(private readonly prisma: PrismaService) {}
constructor(
private readonly prisma: PrismaService,
private readonly revalidationService: RevalidationService,
) {}
/**
* 1. Submit a new review for a product (User/Guest)
@@ -203,6 +207,7 @@ export class ReviewsService {
async updateReviewStatus(id: string, dto: UpdateReviewDto) {
const review = await this.prisma.productReview.findUnique({
where: { id },
include: { product: { select: { slug: true, artNo: true } } },
});
if (!review) {
@@ -218,6 +223,13 @@ export class ReviewsService {
},
});
if (review.product) {
await this.revalidationService.revalidateProduct(
review.product.slug,
review.product.artNo,
);
}
return {
success: true,
message: 'وضعیت دیدگاه با موفقیت بروزرسانی شد',
@@ -231,6 +243,7 @@ export class ReviewsService {
async deleteReview(id: string) {
const review = await this.prisma.productReview.findUnique({
where: { id },
include: { product: { select: { slug: true, artNo: true } } },
});
if (!review) {
@@ -239,6 +252,13 @@ export class ReviewsService {
await this.prisma.productReview.delete({ where: { id } });
if (review.product) {
await this.revalidationService.revalidateProduct(
review.product.slug,
review.product.artNo,
);
}
return {
success: true,
message: 'دیدگاه با موفقیت حذف شد',