canina/backend/src/wiki/wiki.service.ts
2026-08-07 07:39:26 +03:30

60 lines
1.5 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 WikiService {
constructor(private prisma: PrismaService) {}
async findAll(filters: PaginationDto) {
const {
search,
page = 1,
limit = 10,
sortBy: rawSortBy = 'term',
sortOrder = 'asc',
} = filters;
const allowedSortFields = ['key', 'term', 'wikiId'];
const sortBy = allowedSortFields.includes(rawSortBy) ? rawSortBy : 'term';
const whereClause: Prisma.ScientificTermWhereInput = {};
if (search) {
whereClause.OR = [
{ term: { contains: search, mode: 'insensitive' } },
{ definition: { contains: search, mode: 'insensitive' } },
];
}
const skip = (page - 1) * limit;
const [data, total] = await Promise.all([
this.prisma.scientificTerm.findMany({
where: whereClause,
skip,
take: limit,
orderBy: { [sortBy]: sortOrder },
}),
this.prisma.scientificTerm.count({ where: whereClause }),
]);
return {
data,
meta: {
total,
page,
lastPage: Math.ceil(total / limit),
limit,
},
};
}
async findOneByKey(key: string) {
const term = await this.prisma.scientificTerm.findUnique({
where: { key },
});
if (!term) throw new NotFoundException('Wiki term not found');
return term;
}
}