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

67 lines
1.8 KiB
TypeScript

import { Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
export class BlogQuery {
page?: number | string;
limit?: number | string;
search?: string;
}
@Injectable()
export class BlogsService {
constructor(private prisma: PrismaService) {}
async getBlogs(query: BlogQuery = {}) {
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 [data, total] = await Promise.all([
this.prisma.blog.findMany({
where,
skip,
take: limit,
orderBy: { createdAt: 'desc' },
include: { author: { select: { firstName: true, lastName: true } } },
}),
this.prisma.blog.count({ where }),
]);
return {
data,
meta: {
total,
page,
limit,
lastPage: Math.ceil(total / limit),
},
};
}
async createBlog(
data: Prisma.BlogCreateWithoutAuthorInput,
authorId: string,
) {
return this.prisma.blog.create({
data: { ...data, author: { connect: { id: authorId } } },
});
}
async updateBlog(id: string, data: Prisma.BlogUpdateInput) {
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 } });
}
}