test: comprehensive test suites and quality gates pass across backend, storefront and admin
- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation. - Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings. - Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors. - Fixed unmount lifecycle guards, promise error handling, and component edge cases.
This commit is contained in:
1 parent
1e73715169
commit
ddbf1ca026
439 files changed
+32911
-6107
No files matched your search
@@ -0,0 +1,212 @@
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { BlogsController } from "./blogs.controller";
|
||||
import { BlogsService } from "./blogs.service";
|
||||
import { PaginationDto } from "../common/dto/pagination.dto";
|
||||
|
||||
describe("BlogsController", () => {
|
||||
let controller: BlogsController;
|
||||
let service: BlogsService;
|
||||
|
||||
const mockBlogsService = {
|
||||
findAll: jest.fn(),
|
||||
getCategories: jest.fn(),
|
||||
getTags: jest.fn(),
|
||||
findHomepage: jest.fn(),
|
||||
findOneBySlug: jest.fn(),
|
||||
incrementView: jest.fn(),
|
||||
findCommentsBySlug: jest.fn(),
|
||||
addComment: jest.fn(),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [BlogsController],
|
||||
providers: [
|
||||
{
|
||||
provide: BlogsService,
|
||||
useValue: mockBlogsService,
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<BlogsController>(BlogsController);
|
||||
service = module.get<BlogsService>(BlogsService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should be defined", () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
|
||||
describe("findAll", () => {
|
||||
it("should forward pagination and search query to service.findAll", async () => {
|
||||
const query: PaginationDto = {
|
||||
page: 1,
|
||||
limit: 10,
|
||||
search: "تغذیه سگ",
|
||||
};
|
||||
|
||||
const expectedResponse = {
|
||||
data: [
|
||||
{
|
||||
id: "blog-1",
|
||||
title: "راهنمای جامع تغذیه سگهای نژاد بزرگ",
|
||||
slug: "dog-nutrition-guide",
|
||||
isPublished: true,
|
||||
},
|
||||
],
|
||||
meta: {
|
||||
total: 1,
|
||||
page: 1,
|
||||
lastPage: 1,
|
||||
limit: 10,
|
||||
},
|
||||
};
|
||||
|
||||
mockBlogsService.findAll.mockResolvedValue(expectedResponse);
|
||||
|
||||
const result = await controller.findAll(query);
|
||||
|
||||
expect(service.findAll).toHaveBeenCalledWith(query);
|
||||
expect(result).toEqual(expectedResponse);
|
||||
});
|
||||
});
|
||||
|
||||
describe("findCategories", () => {
|
||||
it("should return blog categories from service.getCategories", async () => {
|
||||
const categories = [
|
||||
{ id: "cat-1", name: "سلامت مفاصل", slug: "joint-health" },
|
||||
{ id: "cat-2", name: "مکملهای تخصصی", slug: "supplements" },
|
||||
];
|
||||
|
||||
mockBlogsService.getCategories.mockResolvedValue(categories);
|
||||
|
||||
const result = await controller.findCategories();
|
||||
|
||||
expect(service.getCategories).toHaveBeenCalledTimes(1);
|
||||
expect(result).toEqual(categories);
|
||||
});
|
||||
});
|
||||
|
||||
describe("findTags", () => {
|
||||
it("should return blog tags from service.getTags", async () => {
|
||||
const tags = [
|
||||
{ id: "tag-1", name: "کانینا", slug: "canina" },
|
||||
{ id: "tag-2", name: "ویتامین", slug: "vitamins" },
|
||||
];
|
||||
|
||||
mockBlogsService.getTags.mockResolvedValue(tags);
|
||||
|
||||
const result = await controller.findTags();
|
||||
|
||||
expect(service.getTags).toHaveBeenCalledTimes(1);
|
||||
expect(result).toEqual(tags);
|
||||
});
|
||||
});
|
||||
|
||||
describe("findHomepage", () => {
|
||||
it("should return curated homepage blog posts", async () => {
|
||||
const homepageData = {
|
||||
mode: "selected",
|
||||
blogs: [
|
||||
{
|
||||
id: "blog-1",
|
||||
title: "چرا گلوکوزامین برای مفاصل سگ حیاتی است؟",
|
||||
slug: "glucosamine-benefits",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
mockBlogsService.findHomepage.mockResolvedValue(homepageData);
|
||||
|
||||
const result = await controller.findHomepage();
|
||||
|
||||
expect(service.findHomepage).toHaveBeenCalledTimes(1);
|
||||
expect(result).toEqual(homepageData);
|
||||
});
|
||||
});
|
||||
|
||||
describe("findOne", () => {
|
||||
it("should return single blog details by slug", async () => {
|
||||
const slug = "glucosamine-benefits";
|
||||
const expectedBlog = {
|
||||
id: "blog-1",
|
||||
title: "چرا گلوکوزامین برای مفاصل سگ حیاتی است؟",
|
||||
slug,
|
||||
content: "متن کامل مقاله...",
|
||||
viewCount: 120,
|
||||
};
|
||||
|
||||
mockBlogsService.findOneBySlug.mockResolvedValue(expectedBlog);
|
||||
|
||||
const result = await controller.findOne(slug);
|
||||
|
||||
expect(service.findOneBySlug).toHaveBeenCalledWith(slug);
|
||||
expect(result).toEqual(expectedBlog);
|
||||
});
|
||||
});
|
||||
|
||||
describe("incrementView", () => {
|
||||
it("should register view count increment by slug", async () => {
|
||||
const slug = "glucosamine-benefits";
|
||||
const expectedResponse = { success: true, viewCount: 121 };
|
||||
|
||||
mockBlogsService.incrementView.mockResolvedValue(expectedResponse);
|
||||
|
||||
const result = await controller.incrementView(slug);
|
||||
|
||||
expect(service.incrementView).toHaveBeenCalledWith(slug);
|
||||
expect(result).toEqual(expectedResponse);
|
||||
});
|
||||
});
|
||||
|
||||
describe("findComments", () => {
|
||||
it("should return approved comments for a specific blog post", async () => {
|
||||
const slug = "glucosamine-benefits";
|
||||
const comments = [
|
||||
{
|
||||
id: "comm-1",
|
||||
userName: "سارا احمدی",
|
||||
content: "بسیار مقاله آموزندهای بود.",
|
||||
status: "APPROVED",
|
||||
},
|
||||
];
|
||||
|
||||
mockBlogsService.findCommentsBySlug.mockResolvedValue(comments);
|
||||
|
||||
const result = await controller.findComments(slug);
|
||||
|
||||
expect(service.findCommentsBySlug).toHaveBeenCalledWith(slug);
|
||||
expect(result).toEqual(comments);
|
||||
});
|
||||
});
|
||||
|
||||
describe("addComment", () => {
|
||||
it("should submit a new comment for a blog post", async () => {
|
||||
const slug = "glucosamine-benefits";
|
||||
const body = {
|
||||
userName: "امیرحسین رضایی",
|
||||
email: "amir@example.com",
|
||||
content: "آیا این مکمل برای گربهها هم قابل استفاده است؟",
|
||||
userId: "user-123",
|
||||
};
|
||||
|
||||
const createdComment = {
|
||||
id: "comm-2",
|
||||
blogId: "blog-1",
|
||||
...body,
|
||||
status: "PENDING",
|
||||
};
|
||||
|
||||
mockBlogsService.addComment.mockResolvedValue(createdComment);
|
||||
|
||||
const result = await controller.addComment(slug, body);
|
||||
|
||||
expect(service.addComment).toHaveBeenCalledWith(slug, body);
|
||||
expect(result).toEqual(createdComment);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -8,8 +8,8 @@ import {
|
||||
Query,
|
||||
UseGuards,
|
||||
Request,
|
||||
} from '@nestjs/common';
|
||||
import { BlogsService } from './blogs.service';
|
||||
} from "@nestjs/common";
|
||||
import { BlogsService } from "./blogs.service";
|
||||
import {
|
||||
ApiTags,
|
||||
ApiOperation,
|
||||
@@ -17,71 +17,71 @@ import {
|
||||
ApiOkResponse,
|
||||
ApiNotFoundResponse,
|
||||
ApiBearerAuth,
|
||||
} from '@nestjs/swagger';
|
||||
import { PaginationDto } from '../common/dto/pagination.dto';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { Throttle } from '@nestjs/throttler';
|
||||
} from "@nestjs/swagger";
|
||||
import { PaginationDto } from "../common/dto/pagination.dto";
|
||||
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
|
||||
import { Throttle } from "@nestjs/throttler";
|
||||
|
||||
@ApiTags('Blogs - مجله سلامت')
|
||||
@Controller('blogs')
|
||||
@ApiTags("Blogs - مجله سلامت")
|
||||
@Controller("blogs")
|
||||
@ApiResponse({
|
||||
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
description: 'خطای داخلی سرور',
|
||||
description: "خطای داخلی سرور",
|
||||
})
|
||||
export class BlogsController {
|
||||
constructor(private readonly blogsService: BlogsService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'دریافت لیست مقالات مجله سلامت' })
|
||||
@ApiOkResponse({ description: 'لیست مقالات منتشر شده (صفحهبندی شده)' })
|
||||
@ApiOperation({ summary: "دریافت لیست مقالات مجله سلامت" })
|
||||
@ApiOkResponse({ description: "لیست مقالات منتشر شده (صفحهبندی شده)" })
|
||||
findAll(@Query() query: PaginationDto) {
|
||||
return this.blogsService.findAll(query);
|
||||
}
|
||||
|
||||
@Get('categories')
|
||||
@ApiOperation({ summary: 'دریافت لیست دستهبندیهای وبلاگ' })
|
||||
@Get("categories")
|
||||
@ApiOperation({ summary: "دریافت لیست دستهبندیهای وبلاگ" })
|
||||
findCategories() {
|
||||
return this.blogsService.getCategories();
|
||||
}
|
||||
|
||||
@Get('tags')
|
||||
@ApiOperation({ summary: 'دریافت لیست تگهای وبلاگ' })
|
||||
@Get("tags")
|
||||
@ApiOperation({ summary: "دریافت لیست تگهای وبلاگ" })
|
||||
findTags() {
|
||||
return this.blogsService.getTags();
|
||||
}
|
||||
|
||||
@Get('homepage')
|
||||
@ApiOperation({ summary: 'دریافت مقالات برای نمایش در صفحه اصلی' })
|
||||
@ApiOkResponse({ description: 'مقالات انتخاب شده برای صفحه اصلی' })
|
||||
@Get("homepage")
|
||||
@ApiOperation({ summary: "دریافت مقالات برای نمایش در صفحه اصلی" })
|
||||
@ApiOkResponse({ description: "مقالات انتخاب شده برای صفحه اصلی" })
|
||||
findHomepage() {
|
||||
return this.blogsService.findHomepage();
|
||||
}
|
||||
|
||||
@Get(':slug')
|
||||
@ApiOperation({ summary: 'دریافت مقاله با اسلاگ (Slug)' })
|
||||
@ApiOkResponse({ description: 'اطلاعات کامل مقاله' })
|
||||
@ApiNotFoundResponse({ description: 'مقاله یافت نشد' })
|
||||
findOne(@Param('slug') slug: string) {
|
||||
@Get(":slug")
|
||||
@ApiOperation({ summary: "دریافت مقاله با اسلاگ (Slug)" })
|
||||
@ApiOkResponse({ description: "اطلاعات کامل مقاله" })
|
||||
@ApiNotFoundResponse({ description: "مقاله یافت نشد" })
|
||||
findOne(@Param("slug") slug: string) {
|
||||
return this.blogsService.findOneBySlug(slug);
|
||||
}
|
||||
|
||||
@Post(':slug/view')
|
||||
@ApiOperation({ summary: 'ثبت و افزایش بازدید مقاله' })
|
||||
incrementView(@Param('slug') slug: string) {
|
||||
@Post(":slug/view")
|
||||
@ApiOperation({ summary: "ثبت و افزایش بازدید مقاله" })
|
||||
incrementView(@Param("slug") slug: string) {
|
||||
return this.blogsService.incrementView(slug);
|
||||
}
|
||||
|
||||
@Get(':slug/comments')
|
||||
@ApiOperation({ summary: 'دریافت نظرات تأیید شده مقاله' })
|
||||
findComments(@Param('slug') slug: string) {
|
||||
@Get(":slug/comments")
|
||||
@ApiOperation({ summary: "دریافت نظرات تأیید شده مقاله" })
|
||||
findComments(@Param("slug") slug: string) {
|
||||
return this.blogsService.findCommentsBySlug(slug);
|
||||
}
|
||||
|
||||
@Throttle({ default: { limit: 10, ttl: 60000 } })
|
||||
@Post(':slug/comments')
|
||||
@ApiOperation({ summary: 'ارسال نظر برای مقاله' })
|
||||
@Post(":slug/comments")
|
||||
@ApiOperation({ summary: "ارسال نظر برای مقاله" })
|
||||
addComment(
|
||||
@Param('slug') slug: string,
|
||||
@Param("slug") slug: string,
|
||||
@Body()
|
||||
body: {
|
||||
userName: string;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { BlogsService } from './blogs.service';
|
||||
import { BlogsController } from './blogs.controller';
|
||||
import { Module } from "@nestjs/common";
|
||||
import { BlogsService } from "./blogs.service";
|
||||
import { BlogsController } from "./blogs.controller";
|
||||
|
||||
@Module({
|
||||
controllers: [BlogsController],
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { BlogsService } from "./blogs.service";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { NotFoundException } from "@nestjs/common";
|
||||
|
||||
describe("BlogsService", () => {
|
||||
let service: BlogsService;
|
||||
|
||||
const mockPrisma = {
|
||||
blog: {
|
||||
findMany: jest.fn(),
|
||||
count: jest.fn(),
|
||||
findFirst: jest.fn(),
|
||||
update: jest.fn(),
|
||||
},
|
||||
product: {
|
||||
findMany: jest.fn().mockResolvedValue([]),
|
||||
},
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
BlogsService,
|
||||
{
|
||||
provide: PrismaService,
|
||||
useValue: mockPrisma,
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<BlogsService>(BlogsService);
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should be defined", () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
describe("findAll", () => {
|
||||
it("should query published blogs with pagination", async () => {
|
||||
const blogs = [
|
||||
{ id: "1", title: "Blog 1", isPublished: true, status: "PUBLISHED" },
|
||||
];
|
||||
mockPrisma.blog.findMany.mockResolvedValue(blogs);
|
||||
mockPrisma.blog.count.mockResolvedValue(1);
|
||||
|
||||
const result = await service.findAll({ page: 1, limit: 10 });
|
||||
expect(mockPrisma.blog.findMany).toHaveBeenCalled();
|
||||
expect(result.data).toEqual(blogs);
|
||||
expect(result.meta.total).toBe(1);
|
||||
});
|
||||
|
||||
it("should filter by categorySlug and search term", async () => {
|
||||
mockPrisma.blog.findMany.mockResolvedValue([]);
|
||||
mockPrisma.blog.count.mockResolvedValue(0);
|
||||
|
||||
await service.findAll({ categorySlug: "nutrition", search: "dog" });
|
||||
expect(mockPrisma.blog.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({
|
||||
category: { slug: "nutrition" },
|
||||
AND: expect.any(Array),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("findHomepage", () => {
|
||||
it("should return selected blogs if showOnHome posts exist", async () => {
|
||||
const selected = [{ id: "b1", title: "Hero Blog", showOnHome: true }];
|
||||
mockPrisma.blog.findMany.mockResolvedValueOnce(selected);
|
||||
|
||||
const result = await service.findHomepage();
|
||||
expect(result.mode).toBe("selected");
|
||||
expect(result.blogs).toEqual(selected);
|
||||
});
|
||||
|
||||
it("should fallback to newest blogs if no showOnHome posts exist", async () => {
|
||||
const newest = [{ id: "b2", title: "Newest Blog" }];
|
||||
mockPrisma.blog.findMany
|
||||
.mockResolvedValueOnce([])
|
||||
.mockResolvedValueOnce(newest);
|
||||
|
||||
const result = await service.findHomepage();
|
||||
expect(result.mode).toBe("newest");
|
||||
expect(result.blogs).toEqual(newest);
|
||||
});
|
||||
});
|
||||
|
||||
describe("findOneBySlug", () => {
|
||||
it("should throw NotFoundException if slug is empty or blog not found", async () => {
|
||||
mockPrisma.blog.findFirst.mockResolvedValue(null);
|
||||
await expect(service.findOneBySlug("unknown-slug")).rejects.toThrow(
|
||||
NotFoundException,
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw NotFoundException if blog is not published or draft", async () => {
|
||||
mockPrisma.blog.findFirst.mockResolvedValue({
|
||||
id: "1",
|
||||
slug: "draft-post",
|
||||
isPublished: false,
|
||||
status: "DRAFT",
|
||||
});
|
||||
await expect(service.findOneBySlug("draft-post")).rejects.toThrow(
|
||||
NotFoundException,
|
||||
);
|
||||
});
|
||||
|
||||
it("should return published blog and increment view count asynchronously", async () => {
|
||||
const blog = {
|
||||
id: "1",
|
||||
slug: "dog-vitamins",
|
||||
isPublished: true,
|
||||
status: "PUBLISHED",
|
||||
publishedAt: new Date(Date.now() - 10000),
|
||||
relatedProductIds: [],
|
||||
};
|
||||
mockPrisma.blog.findFirst.mockResolvedValue(blog);
|
||||
mockPrisma.blog.update.mockResolvedValue({});
|
||||
|
||||
const result = await service.findOneBySlug("dog-vitamins");
|
||||
expect(result.id).toBe("1");
|
||||
expect(mockPrisma.blog.update).toHaveBeenCalledWith({
|
||||
where: { id: "1" },
|
||||
data: { viewCount: { increment: 1 } },
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
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 { Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { PaginationDto } from "../common/dto/pagination.dto";
|
||||
|
||||
export interface BlogFilterDto extends PaginationDto {
|
||||
categorySlug?: string;
|
||||
@@ -18,8 +18,8 @@ export class BlogsService {
|
||||
search,
|
||||
page = 1,
|
||||
limit = 10,
|
||||
sortBy = 'publishedAt',
|
||||
sortOrder = 'desc',
|
||||
sortBy = "publishedAt",
|
||||
sortOrder = "desc",
|
||||
categorySlug,
|
||||
tagSlug,
|
||||
featured,
|
||||
@@ -28,7 +28,7 @@ export class BlogsService {
|
||||
const now = new Date();
|
||||
const whereClause: Prisma.BlogWhereInput = {
|
||||
isPublished: true,
|
||||
status: 'PUBLISHED',
|
||||
status: "PUBLISHED",
|
||||
OR: [{ publishedAt: null }, { publishedAt: { lte: now } }],
|
||||
};
|
||||
|
||||
@@ -36,10 +36,10 @@ export class BlogsService {
|
||||
whereClause.AND = [
|
||||
{
|
||||
OR: [
|
||||
{ title: { contains: search, mode: 'insensitive' } },
|
||||
{ excerpt: { contains: search, mode: 'insensitive' } },
|
||||
{ content: { contains: search, mode: 'insensitive' } },
|
||||
{ keywords: { contains: search, mode: 'insensitive' } },
|
||||
{ title: { contains: search, mode: "insensitive" } },
|
||||
{ excerpt: { contains: search, mode: "insensitive" } },
|
||||
{ content: { contains: search, mode: "insensitive" } },
|
||||
{ keywords: { contains: search, mode: "insensitive" } },
|
||||
],
|
||||
},
|
||||
];
|
||||
@@ -53,8 +53,8 @@ export class BlogsService {
|
||||
whereClause.tags = { some: { slug: tagSlug } };
|
||||
}
|
||||
|
||||
if (featured !== undefined && featured !== '') {
|
||||
whereClause.featured = String(featured) === 'true';
|
||||
if (featured !== undefined && featured !== "") {
|
||||
whereClause.featured = String(featured) === "true";
|
||||
}
|
||||
|
||||
const skip = (Number(page) - 1) * Number(limit);
|
||||
@@ -65,7 +65,7 @@ export class BlogsService {
|
||||
skip,
|
||||
take: Number(limit),
|
||||
orderBy: {
|
||||
[sortBy === 'createdAt' ? 'createdAt' : 'publishedAt']: sortOrder,
|
||||
[sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder,
|
||||
},
|
||||
include: {
|
||||
author: {
|
||||
@@ -78,7 +78,7 @@ export class BlogsService {
|
||||
select: { id: true, name: true, slug: true },
|
||||
},
|
||||
_count: {
|
||||
select: { comments: { where: { status: 'APPROVED' } } },
|
||||
select: { comments: { where: { status: "APPROVED" } } },
|
||||
},
|
||||
},
|
||||
}),
|
||||
@@ -100,7 +100,7 @@ export class BlogsService {
|
||||
const now = new Date();
|
||||
const baseWhere: Prisma.BlogWhereInput = {
|
||||
isPublished: true,
|
||||
status: 'PUBLISHED',
|
||||
status: "PUBLISHED",
|
||||
OR: [{ publishedAt: null }, { publishedAt: { lte: now } }],
|
||||
};
|
||||
|
||||
@@ -108,38 +108,38 @@ export class BlogsService {
|
||||
const selectedBlogs = await this.prisma.blog.findMany({
|
||||
where: { ...baseWhere, showOnHome: true },
|
||||
take: 4,
|
||||
orderBy: { publishedAt: 'desc' },
|
||||
orderBy: { publishedAt: "desc" },
|
||||
include: {
|
||||
author: { select: { firstName: true, lastName: true } },
|
||||
category: { select: { id: true, name: true, slug: true } },
|
||||
tags: { select: { id: true, name: true, slug: true } },
|
||||
_count: { select: { comments: { where: { status: 'APPROVED' } } } },
|
||||
_count: { select: { comments: { where: { status: "APPROVED" } } } },
|
||||
},
|
||||
});
|
||||
|
||||
if (selectedBlogs.length > 0) {
|
||||
return { mode: 'selected', blogs: selectedBlogs };
|
||||
return { mode: "selected", blogs: selectedBlogs };
|
||||
}
|
||||
|
||||
// Fallback: return newest published blogs
|
||||
const newestBlogs = await this.prisma.blog.findMany({
|
||||
where: baseWhere,
|
||||
take: 4,
|
||||
orderBy: { publishedAt: 'desc' },
|
||||
orderBy: { publishedAt: "desc" },
|
||||
include: {
|
||||
author: { select: { firstName: true, lastName: true } },
|
||||
category: { select: { id: true, name: true, slug: true } },
|
||||
tags: { select: { id: true, name: true, slug: true } },
|
||||
_count: { select: { comments: { where: { status: 'APPROVED' } } } },
|
||||
_count: { select: { comments: { where: { status: "APPROVED" } } } },
|
||||
},
|
||||
});
|
||||
|
||||
return { mode: 'newest', blogs: newestBlogs };
|
||||
return { mode: "newest", blogs: newestBlogs };
|
||||
}
|
||||
|
||||
async findOneBySlug(rawSlug: string) {
|
||||
if (!rawSlug) {
|
||||
throw new NotFoundException('مقاله یافت نشد');
|
||||
throw new NotFoundException("مقاله یافت نشد");
|
||||
}
|
||||
|
||||
let decodedSlug = rawSlug;
|
||||
@@ -173,24 +173,24 @@ export class BlogsService {
|
||||
select: { id: true, name: true, slug: true },
|
||||
},
|
||||
_count: {
|
||||
select: { comments: { where: { status: 'APPROVED' } } },
|
||||
select: { comments: { where: { status: "APPROVED" } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!blog) {
|
||||
throw new NotFoundException('مقاله یافت نشد');
|
||||
throw new NotFoundException("مقاله یافت نشد");
|
||||
}
|
||||
|
||||
// Public route must not expose scheduled, draft, or future published posts
|
||||
const now = new Date();
|
||||
const isReady =
|
||||
blog.isPublished &&
|
||||
blog.status === 'PUBLISHED' &&
|
||||
blog.status === "PUBLISHED" &&
|
||||
(!blog.publishedAt || blog.publishedAt <= now);
|
||||
|
||||
if (!isReady) {
|
||||
throw new NotFoundException('مقاله یافت نشد');
|
||||
throw new NotFoundException("مقاله یافت نشد");
|
||||
}
|
||||
|
||||
// Fetch related products safely
|
||||
@@ -202,7 +202,7 @@ export class BlogsService {
|
||||
) {
|
||||
const validProductUuids = blog.relatedProductIds.filter(
|
||||
(id) =>
|
||||
typeof id === 'string' &&
|
||||
typeof id === "string" &&
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
|
||||
id,
|
||||
),
|
||||
@@ -223,7 +223,7 @@ export class BlogsService {
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('[BlogsService] Error fetching related products:', err);
|
||||
console.warn("[BlogsService] Error fetching related products:", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -237,7 +237,7 @@ export class BlogsService {
|
||||
) {
|
||||
const validBlogUuids = blog.relatedBlogIds.filter(
|
||||
(id) =>
|
||||
typeof id === 'string' &&
|
||||
typeof id === "string" &&
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
|
||||
id,
|
||||
),
|
||||
@@ -248,7 +248,7 @@ export class BlogsService {
|
||||
where: {
|
||||
id: { in: validBlogUuids },
|
||||
isPublished: true,
|
||||
status: 'PUBLISHED',
|
||||
status: "PUBLISHED",
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
@@ -262,7 +262,7 @@ export class BlogsService {
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('[BlogsService] Error fetching related blogs:', err);
|
||||
console.warn("[BlogsService] Error fetching related blogs:", err);
|
||||
}
|
||||
}
|
||||
} else if (blog.categoryId) {
|
||||
@@ -272,7 +272,7 @@ export class BlogsService {
|
||||
categoryId: blog.categoryId,
|
||||
id: { not: blog.id },
|
||||
isPublished: true,
|
||||
status: 'PUBLISHED',
|
||||
status: "PUBLISHED",
|
||||
},
|
||||
take: 3,
|
||||
select: {
|
||||
@@ -288,7 +288,7 @@ export class BlogsService {
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
'[BlogsService] Error fetching fallback related blogs:',
|
||||
"[BlogsService] Error fetching fallback related blogs:",
|
||||
err,
|
||||
);
|
||||
}
|
||||
@@ -312,12 +312,12 @@ export class BlogsService {
|
||||
|
||||
async getCategories() {
|
||||
return this.prisma.blogCategory.findMany({
|
||||
orderBy: { order: 'asc' },
|
||||
orderBy: { order: "asc" },
|
||||
include: {
|
||||
children: true,
|
||||
_count: {
|
||||
select: {
|
||||
blogs: { where: { isPublished: true, status: 'PUBLISHED' } },
|
||||
blogs: { where: { isPublished: true, status: "PUBLISHED" } },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -326,11 +326,11 @@ export class BlogsService {
|
||||
|
||||
async getTags() {
|
||||
return this.prisma.blogTag.findMany({
|
||||
orderBy: { createdAt: 'desc' },
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: {
|
||||
_count: {
|
||||
select: {
|
||||
blogs: { where: { isPublished: true, status: 'PUBLISHED' } },
|
||||
blogs: { where: { isPublished: true, status: "PUBLISHED" } },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -342,7 +342,7 @@ export class BlogsService {
|
||||
where: { slug },
|
||||
select: { id: true, viewCount: true },
|
||||
});
|
||||
if (!blog) throw new NotFoundException('مقاله یافت نشد');
|
||||
if (!blog) throw new NotFoundException("مقاله یافت نشد");
|
||||
|
||||
const updated = await this.prisma.blog.update({
|
||||
where: { id: blog.id },
|
||||
@@ -358,11 +358,11 @@ export class BlogsService {
|
||||
where: { slug },
|
||||
select: { id: true, allowComments: true },
|
||||
});
|
||||
if (!blog) throw new NotFoundException('مقاله یافت نشد');
|
||||
if (!blog) throw new NotFoundException("مقاله یافت نشد");
|
||||
|
||||
return this.prisma.blogComment.findMany({
|
||||
where: { blogId: blog.id, status: 'APPROVED' },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
where: { blogId: blog.id, status: "APPROVED" },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -379,9 +379,9 @@ export class BlogsService {
|
||||
where: { slug },
|
||||
select: { id: true, allowComments: true },
|
||||
});
|
||||
if (!blog) throw new NotFoundException('مقاله یافت نشد');
|
||||
if (!blog) throw new NotFoundException("مقاله یافت نشد");
|
||||
if (!blog.allowComments) {
|
||||
throw new NotFoundException('ارسال دیدگاه برای این مقاله غیرفعال است');
|
||||
throw new NotFoundException("ارسال دیدگاه برای این مقاله غیرفعال است");
|
||||
}
|
||||
|
||||
return this.prisma.blogComment.create({
|
||||
@@ -390,7 +390,7 @@ export class BlogsService {
|
||||
userName: data.userName,
|
||||
content: data.content,
|
||||
userId: data.userId,
|
||||
status: 'PENDING',
|
||||
status: "PENDING",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { PartialType } from '@nestjs/swagger';
|
||||
import { CreateBlogDto } from './create-blog.dto';
|
||||
import { PartialType } from "@nestjs/swagger";
|
||||
import { CreateBlogDto } from "./create-blog.dto";
|
||||
|
||||
export class UpdateBlogDto extends PartialType(CreateBlogDto) {}
|
||||
Reference in new issue
Block a user