Files
canina/backend/src/blogs/blogs.service.ts
T

72 lines
1.6 KiB
TypeScript

import { Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { PaginationDto } from '../common/dto/pagination.dto';
@Injectable()
export class BlogsService {
constructor(private prisma: PrismaService) {}
async findAll(filters: PaginationDto) {
const {
search,
page = 1,
limit = 10,
sortBy = 'createdAt',
sortOrder = 'desc',
} = filters;
const whereClause: Prisma.BlogWhereInput = { isPublished: true };
if (search) {
whereClause.OR = [
{ title: { contains: search, mode: 'insensitive' } },
{ content: { contains: search, mode: 'insensitive' } },
];
}
const skip = (page - 1) * limit;
const [data, total] = await Promise.all([
this.prisma.blog.findMany({
where: whereClause,
skip,
take: limit,
orderBy: { [sortBy]: sortOrder },
include: {
author: {
select: { firstName: true, lastName: true },
},
},
}),
this.prisma.blog.count({ where: whereClause }),
]);
return {
data,
meta: {
total,
page,
lastPage: Math.ceil(total / limit),
limit,
},
};
}
async findOneBySlug(slug: string) {
const blog = await this.prisma.blog.findUnique({
where: { slug, isPublished: true },
include: {
author: {
select: { firstName: true, lastName: true },
},
},
});
if (!blog) {
throw new NotFoundException('مقاله یافت نشد');
}
return blog;
}
}