canina/backend/src/admin/blogs.service.ts

49 lines
1.5 KiB
TypeScript

import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
@Injectable()
export class BlogsService {
constructor(private prisma: PrismaService) {}
async getBlogs(query: any) {
const { page = 1, limit = 10, search = '' } = query;
const skip = (Number(page) - 1) * Number(limit);
const where = search ? { title: { contains: search, mode: 'insensitive' as any } } : {};
const [data, total] = await Promise.all([
this.prisma.blog.findMany({
where,
skip,
take: Number(limit),
orderBy: { createdAt: 'desc' },
include: { author: { select: { firstName: true, lastName: true } } }
}),
this.prisma.blog.count({ where })
]);
return {
data,
meta: { total, page: Number(page), limit: Number(limit), lastPage: Math.ceil(total / Number(limit)) }
};
}
async createBlog(data: any, authorId: string) {
return this.prisma.blog.create({
data: { ...data, authorId }
});
}
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 });
}
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 } });
}
}