89 lines
2.5 KiB
TypeScript
89 lines
2.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";
|
|
import {
|
|
createPaginationMeta,
|
|
extractSearchTokens,
|
|
calculateRelevanceScore,
|
|
} from "../common/utils/search.utils";
|
|
|
|
@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 = {};
|
|
const tokens = extractSearchTokens(search);
|
|
if (tokens.length > 0) {
|
|
const mode = "insensitive" as const;
|
|
whereClause.OR = [
|
|
{ term: { contains: search, mode } },
|
|
{ key: { contains: search, mode } },
|
|
{ definition: { contains: search, mode } },
|
|
...tokens.flatMap((token) => [
|
|
{ term: { contains: token, mode } },
|
|
{ key: { contains: token, mode } },
|
|
]),
|
|
];
|
|
}
|
|
|
|
const safePage = Math.max(1, Number(page) || 1);
|
|
const safeLimit = Math.max(1, Number(limit) || 10);
|
|
const skip = (safePage - 1) * safeLimit;
|
|
|
|
const [rawTerms, total] = await Promise.all([
|
|
this.prisma.scientificTerm.findMany({
|
|
where: whereClause,
|
|
skip: tokens.length > 0 ? undefined : skip,
|
|
take: tokens.length > 0 ? 100 : safeLimit,
|
|
orderBy: { [sortBy]: sortOrder },
|
|
}),
|
|
this.prisma.scientificTerm.count({ where: whereClause }),
|
|
]);
|
|
|
|
let data = rawTerms;
|
|
if (tokens.length > 0 && search) {
|
|
data = [...rawTerms]
|
|
.map((t) => ({
|
|
term: t,
|
|
score: calculateRelevanceScore(
|
|
{
|
|
slug: t.key,
|
|
title: t.term,
|
|
description: t.definition,
|
|
},
|
|
search,
|
|
tokens,
|
|
),
|
|
}))
|
|
.sort((a, b) => b.score - a.score)
|
|
.map((item) => item.term)
|
|
.slice(skip, skip + safeLimit);
|
|
}
|
|
|
|
return {
|
|
data,
|
|
meta: createPaginationMeta(total, safePage, safeLimit),
|
|
};
|
|
}
|
|
|
|
async findOneByKey(key: string) {
|
|
const term = await this.prisma.scientificTerm.findUnique({
|
|
where: { key },
|
|
});
|
|
if (!term) throw new NotFoundException("Wiki term not found");
|
|
return term;
|
|
}
|
|
}
|