feat(blog): complete full-stack blog module with rich text editor, SEO analyzer, JSON-LD schema, and RSS feed
Deploy Canina / deploy (push) Successful in 1m43s

This commit is contained in:
parsa aghaei committed 2026-08-24 16:48:31 +03:30
1 parent eb63d22ac4
commit 5705354429
23 files changed
+124946 -120969

No files matched your search

+73 -3
View File
@@ -34,14 +34,84 @@ export class BlogsController {
@ApiQuery({ name: 'page', required: false })
@ApiQuery({ name: 'limit', required: false })
@ApiQuery({ name: 'search', required: false })
async getBlogs(@Query() query: PaginationDto) {
@ApiQuery({ name: 'status', required: false })
@ApiQuery({ name: 'categoryId', required: false })
async getBlogs(
@Query() query: PaginationDto & { status?: string; categoryId?: string; tagId?: string },
) {
return this.blogsService.getBlogs(query);
}
@Get('authors')
@ApiOperation({ summary: 'لیست کاربران برای انتخاب به عنوان نویسنده' })
async getAuthors() {
const data = await this.blogsService.getAuthors();
return { success: true, data };
}
@Get('categories')
@ApiOperation({ summary: 'لیست دسته‌بندی‌های وبلاگ' })
async getBlogCategories() {
const data = await this.blogsService.getBlogCategories();
return { success: true, data };
}
@Post('categories')
@ApiOperation({ summary: 'ایجاد دسته‌بندی جدید برای وبلاگ' })
async createBlogCategory(@Body() body: Prisma.BlogCategoryCreateInput) {
const data = await this.blogsService.createBlogCategory(body);
return { success: true, data };
}
@Put('categories/:id')
@ApiOperation({ summary: 'ویرایش دسته‌بندی وبلاگ' })
async updateBlogCategory(
@Param('id') id: string,
@Body() body: Prisma.BlogCategoryUpdateInput,
) {
const data = await this.blogsService.updateBlogCategory(id, body);
return { success: true, data };
}
@Delete('categories/:id')
@ApiOperation({ summary: 'حذف دسته‌بندی وبلاگ' })
async deleteBlogCategory(@Param('id') id: string) {
await this.blogsService.deleteBlogCategory(id);
return { success: true };
}
@Get('tags')
@ApiOperation({ summary: 'لیست تگ‌های وبلاگ' })
async getBlogTags() {
const data = await this.blogsService.getBlogTags();
return { success: true, data };
}
@Post('tags')
@ApiOperation({ summary: 'ایجاد تگ جدید برای وبلاگ' })
async createBlogTag(@Body() body: { name: string; slug?: string }) {
const data = await this.blogsService.createBlogTag(body);
return { success: true, data };
}
@Delete('tags/:id')
@ApiOperation({ summary: 'حذف تگ وبلاگ' })
async deleteBlogTag(@Param('id') id: string) {
await this.blogsService.deleteBlogTag(id);
return { success: true };
}
@Get(':id')
@ApiOperation({ summary: 'دریافت مشخصات یک مقاله' })
async getBlogById(@Param('id') id: string) {
const data = await this.blogsService.getBlogById(id);
return { success: true, data };
}
@Post()
@ApiOperation({ summary: 'ایجاد مقاله جدید' })
async createBlog(
@Body() body: Prisma.BlogCreateWithoutAuthorInput,
@Body() body: any,
@Request() req: { user: { id: string } },
) {
const data = await this.blogsService.createBlog(body, req.user.id);
@@ -52,7 +122,7 @@ export class BlogsController {
@ApiOperation({ summary: 'ویرایش مقاله' })
async updateBlog(
@Param('id') id: string,
@Body() body: Prisma.BlogUpdateInput,
@Body() body: any,
) {
const data = await this.blogsService.updateBlog(id, body);
return { success: true, data };
+183 -14
View File
@@ -7,14 +7,28 @@ import { PaginationDto } from '../common/dto/pagination.dto';
export class BlogsService {
constructor(private prisma: PrismaService) {}
async getBlogs(query: PaginationDto) {
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;
const where: Prisma.BlogWhereInput = query.search
? { title: { contains: query.search, mode: 'insensitive' } }
: {};
const where: Prisma.BlogWhereInput = {};
if (query.search) {
where.OR = [
{ title: { contains: query.search, mode: 'insensitive' } },
{ excerpt: { contains: query.search, mode: 'insensitive' } },
{ slug: { contains: query.search, mode: 'insensitive' } },
];
}
if (query.status) {
where.status = query.status;
}
if (query.categoryId) {
where.categoryId = query.categoryId;
}
const [data, total] = await Promise.all([
this.prisma.blog.findMany({
@@ -23,7 +37,9 @@ export class BlogsService {
take: limit,
orderBy: { createdAt: 'desc' },
include: {
author: { select: { firstName: true, lastName: 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 } },
},
}),
@@ -36,24 +52,124 @@ export class BlogsService {
total,
page,
limit,
lastPage: Math.ceil(total / limit),
lastPage: Math.ceil(total / limit) || 1,
},
};
}
async createBlog(
data: Prisma.BlogCreateWithoutAuthorInput,
authorId: string,
) {
async getBlogById(id: string) {
const blog = await this.prisma.blog.findUnique({
where: { id },
include: {
author: { select: { id: true, firstName: true, lastName: true } },
category: true,
tags: true,
},
});
if (!blog) throw new NotFoundException('Blog not found');
return blog;
}
async createBlog(data: any, currentUserId: string) {
const {
tags,
tagNames,
categoryId,
authorId,
publishedAt,
readingTime,
...rest
} = data;
// Connect or create tags
const tagConnectOrCreate = [];
if (Array.isArray(tagNames) && tagNames.length > 0) {
for (const tName of tagNames) {
const trimmed = String(tName).trim();
if (trimmed) {
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()}` },
});
}
}
}
const targetAuthorId = authorId || currentUserId;
const createPayload: Prisma.BlogCreateInput = {
...rest,
readingTime: readingTime ? Number(readingTime) : 3,
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 } } : {}),
};
return this.prisma.blog.create({
data: { ...data, author: { connect: { id: authorId } } },
data: createPayload,
include: {
author: { select: { firstName: true, lastName: true } },
category: true,
tags: true,
},
});
}
async updateBlog(id: string, data: Prisma.BlogUpdateInput) {
async updateBlog(id: string, data: any) {
const blog = await this.prisma.blog.findUnique({ where: { id } });
if (!blog) throw new NotFoundException('Blog not found');
return this.prisma.blog.update({ where: { id }, data });
const {
tags,
tagNames,
categoryId,
authorId,
publishedAt,
readingTime,
...rest
} = data;
const updatePayload: Prisma.BlogUpdateInput = {
...rest,
...(readingTime !== undefined ? { readingTime: Number(readingTime) } : {}),
...(publishedAt !== undefined ? { publishedAt: publishedAt ? new Date(publishedAt) : null } : {}),
...(authorId ? { author: { connect: { id: authorId } } } : {}),
...(categoryId !== undefined
? categoryId
? { category: { connect: { id: categoryId } } }
: { category: { disconnect: true } }
: {}),
};
if (Array.isArray(tagNames)) {
const tagConnectOrCreate = [];
for (const tName of tagNames) {
const trimmed = String(tName).trim();
if (trimmed) {
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()}` },
});
}
}
updatePayload.tags = {
set: [], // clear previous relations
connectOrCreate: tagConnectOrCreate,
};
}
return this.prisma.blog.update({
where: { id },
data: updatePayload,
include: {
author: { select: { firstName: true, lastName: true } },
category: true,
tags: true,
},
});
}
async deleteBlog(id: string) {
@@ -62,6 +178,59 @@ export class BlogsService {
return this.prisma.blog.delete({ where: { id } });
}
// Authors (Users who can write)
async getAuthors() {
return this.prisma.user.findMany({
select: { id: true, firstName: true, lastName: true, email: true, role: true },
orderBy: { firstName: 'asc' },
});
}
// Blog Categories Management
async getBlogCategories() {
return this.prisma.blogCategory.findMany({
orderBy: { order: 'asc' },
include: {
parent: true,
children: true,
_count: { select: { blogs: true } },
},
});
}
async createBlogCategory(data: Prisma.BlogCategoryCreateInput) {
return this.prisma.blogCategory.create({ data });
}
async updateBlogCategory(id: string, data: Prisma.BlogCategoryUpdateInput) {
return this.prisma.blogCategory.update({ where: { id }, data });
}
async deleteBlogCategory(id: string) {
return this.prisma.blogCategory.delete({ where: { id } });
}
// Blog Tags Management
async getBlogTags() {
return this.prisma.blogTag.findMany({
orderBy: { createdAt: 'desc' },
include: {
_count: { select: { blogs: true } },
},
});
}
async createBlogTag(data: { name: string; slug?: string }) {
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()}` },
});
}
async deleteBlogTag(id: string) {
return this.prisma.blogTag.delete({ where: { id } });
}
// Blog Comments Management
async getComments(query: {
page?: number;
@@ -93,7 +262,7 @@ export class BlogsService {
return {
data,
meta: { total, page, limit, lastPage: Math.ceil(total / limit) },
meta: { total, page, limit, lastPage: Math.ceil(total / limit) || 1 },
};
}
+12
View File
@@ -37,6 +37,18 @@ export class BlogsController {
return this.blogsService.findAll(query);
}
@Get('categories')
@ApiOperation({ summary: 'دریافت لیست دسته‌بندی‌های وبلاگ' })
findCategories() {
return this.blogsService.getCategories();
}
@Get('tags')
@ApiOperation({ summary: 'دریافت لیست تگ‌های وبلاگ' })
findTags() {
return this.blogsService.getTags();
}
@Get('homepage')
@ApiOperation({ summary: 'دریافت مقالات برای نمایش در صفحه اصلی' })
@ApiOkResponse({ description: 'مقالات انتخاب شده برای صفحه اصلی' })
+175 -32
View File
@@ -3,41 +3,83 @@ 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;
tagSlug?: string;
featured?: boolean | string;
}
@Injectable()
export class BlogsService {
constructor(private prisma: PrismaService) {}
async findAll(filters: PaginationDto) {
async findAll(filters: BlogFilterDto) {
const {
search,
page = 1,
limit = 10,
sortBy = 'createdAt',
sortBy = 'publishedAt',
sortOrder = 'desc',
categorySlug,
tagSlug,
featured,
} = filters;
const whereClause: Prisma.BlogWhereInput = { isPublished: true };
const now = new Date();
const whereClause: Prisma.BlogWhereInput = {
isPublished: true,
status: 'PUBLISHED',
OR: [
{ publishedAt: null },
{ publishedAt: { lte: now } },
],
};
if (search) {
whereClause.OR = [
{ title: { contains: search, mode: 'insensitive' } },
{ content: { contains: search, mode: 'insensitive' } },
whereClause.AND = [
{
OR: [
{ title: { contains: search, mode: 'insensitive' } },
{ excerpt: { contains: search, mode: 'insensitive' } },
{ content: { contains: search, mode: 'insensitive' } },
{ keywords: { contains: search, mode: 'insensitive' } },
],
},
];
}
const skip = (page - 1) * limit;
if (categorySlug) {
whereClause.category = { slug: categorySlug };
}
if (tagSlug) {
whereClause.tags = { some: { slug: tagSlug } };
}
if (featured !== undefined && featured !== '') {
whereClause.featured = String(featured) === 'true';
}
const skip = (Number(page) - 1) * Number(limit);
const [data, total] = await Promise.all([
this.prisma.blog.findMany({
where: whereClause,
skip,
take: limit,
orderBy: { [sortBy]: sortOrder },
take: Number(limit),
orderBy: { [sortBy === 'createdAt' ? 'createdAt' : 'publishedAt']: sortOrder },
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: true },
select: { comments: { where: { status: 'APPROVED' } } },
},
},
}),
@@ -48,22 +90,31 @@ export class BlogsService {
data,
meta: {
total,
page,
lastPage: Math.ceil(total / limit),
limit,
page: Number(page),
lastPage: Math.ceil(total / Number(limit)) || 1,
limit: Number(limit),
},
};
}
async findHomepage() {
const now = new Date();
const baseWhere: Prisma.BlogWhereInput = {
isPublished: true,
status: 'PUBLISHED',
OR: [{ publishedAt: null }, { publishedAt: { lte: now } }],
};
// Find blogs that have showOnHome = true (selected mode)
const selectedBlogs = await this.prisma.blog.findMany({
where: { isPublished: true, showOnHome: true },
take: 3,
orderBy: { createdAt: 'desc' },
where: { ...baseWhere, showOnHome: true },
take: 4,
orderBy: { publishedAt: 'desc' },
include: {
author: { select: { firstName: true, lastName: true } },
_count: { select: { comments: true } },
category: { select: { id: true, name: true, slug: true } },
tags: { select: { id: true, name: true, slug: true } },
_count: { select: { comments: { where: { status: 'APPROVED' } } } },
},
});
@@ -71,14 +122,16 @@ export class BlogsService {
return { mode: 'selected', blogs: selectedBlogs };
}
// Fallback: return newest 3 published blogs
// Fallback: return newest published blogs
const newestBlogs = await this.prisma.blog.findMany({
where: { isPublished: true },
take: 3,
orderBy: { createdAt: 'desc' },
where: baseWhere,
take: 4,
orderBy: { publishedAt: 'desc' },
include: {
author: { select: { firstName: true, lastName: true } },
_count: { select: { comments: true } },
category: { select: { id: true, name: true, slug: true } },
tags: { select: { id: true, name: true, slug: true } },
_count: { select: { comments: { where: { status: 'APPROVED' } } } },
},
});
@@ -86,14 +139,21 @@ export class BlogsService {
}
async findOneBySlug(slug: string) {
const now = new Date();
const blog = await this.prisma.blog.findUnique({
where: { slug, isPublished: true },
where: { slug },
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: true },
select: { comments: { where: { status: 'APPROVED' } } },
},
},
});
@@ -102,25 +162,105 @@ export class BlogsService {
throw new NotFoundException('مقاله یافت نشد');
}
// Increment view count
// Fetch related products if any
let relatedProducts: any[] = [];
if (blog.relatedProductIds && blog.relatedProductIds.length > 0) {
relatedProducts = await this.prisma.product.findMany({
where: { id: { in: blog.relatedProductIds } },
select: {
id: true,
nameFa: true,
slug: true,
priceValue: true,
priceDisplay: true,
imageUrl: true,
categorySlug: true,
unit: true,
},
});
}
// Fetch related blogs if any or fallback to same category
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' },
select: {
id: true,
title: true,
slug: true,
imageUrl: true,
readingTime: true,
publishedAt: true,
createdAt: true,
category: { select: { name: true, slug: true } },
},
});
} else if (blog.categoryId) {
relatedBlogs = await this.prisma.blog.findMany({
where: {
categoryId: blog.categoryId,
id: { not: blog.id },
isPublished: true,
status: 'PUBLISHED',
},
take: 3,
select: {
id: true,
title: true,
slug: true,
imageUrl: true,
readingTime: true,
publishedAt: true,
createdAt: true,
category: { select: { name: true, slug: true } },
},
});
}
// Increment view count asynchronously
await this.prisma.blog.update({
where: { id: blog.id },
data: { viewCount: { increment: 1 } },
});
}).catch(() => null);
return { ...blog, viewCount: blog.viewCount + 1 };
return {
...blog,
viewCount: blog.viewCount + 1,
relatedProducts,
relatedBlogs,
};
}
async getCategories() {
return this.prisma.blogCategory.findMany({
orderBy: { order: 'asc' },
include: {
children: true,
_count: { select: { blogs: { where: { isPublished: true, status: 'PUBLISHED' } } } },
},
});
}
async getTags() {
return this.prisma.blogTag.findMany({
orderBy: { createdAt: 'desc' },
include: {
_count: { select: { blogs: { where: { isPublished: true, status: 'PUBLISHED' } } } },
},
});
}
async findCommentsBySlug(slug: string) {
const blog = await this.prisma.blog.findUnique({
where: { slug, isPublished: true },
select: { id: true },
where: { slug },
select: { id: true, allowComments: true },
});
if (!blog) throw new NotFoundException('مقاله یافت نشد');
return this.prisma.blogComment.findMany({
where: { blogId: blog.id, status: 'APPROVED' },
orderBy: { createdAt: 'asc' },
orderBy: { createdAt: 'desc' },
});
}
@@ -129,10 +269,13 @@ export class BlogsService {
data: { userName: string; content: string; userId?: string },
) {
const blog = await this.prisma.blog.findUnique({
where: { slug, isPublished: true },
select: { id: true },
where: { slug },
select: { id: true, allowComments: true },
});
if (!blog) throw new NotFoundException('مقاله یافت نشد');
if (!blog.allowComments) {
throw new NotFoundException('ارسال دیدگاه برای این مقاله غیرفعال است');
}
return this.prisma.blogComment.create({
data: {