refactor(api): pair public tag filters with groups

This commit is contained in:
yeuimu
2026-08-21 10:24:35 +08:00
parent d375df810d
commit 437d9ca93b
3 changed files with 61 additions and 12 deletions
+31 -7
View File
@@ -319,22 +319,46 @@ export class PublicService {
}
private async buildTagGroupFilters(
selectedTagIds: string[],
selectedTagValues: string[],
): Promise<Prisma.GoodWhereInput[]> {
const selected = selectedTagIds.length
const selections = selectedTagValues.map((value) => {
const [tagGroupId, tagId] = value.split(':');
if (!tagGroupId || !tagId || !/^\d+$/.test(tagGroupId) || !/^\d+$/.test(tagId)) {
throw new BadRequestException(
'tagIds 每个元素必须为 tagGroupId:tagId',
);
}
return { tagGroupId, tagId };
});
const uniqueTagIds = [...new Set(selections.map((item) => item.tagId))];
const selected = uniqueTagIds.length
? await this.prisma.tag.findMany({
where: { id: { in: selectedTagIds.map((id) => BigInt(id)) } },
where: { id: { in: uniqueTagIds.map((id) => BigInt(id)) } },
select: { id: true, tagGroupId: true },
})
: [];
if (selected.length !== selectedTagIds.length) {
if (selected.length !== uniqueTagIds.length) {
throw new BadRequestException('包含不存在的标签 ID');
}
const actualGroups = new Map(
selected.map((tag) => [
tag.id.toString(),
tag.tagGroupId?.toString() ?? null,
]),
);
for (const selection of selections) {
if (actualGroups.get(selection.tagId) !== selection.tagGroupId) {
throw new BadRequestException(
`标签 ${selection.tagId} 不属于标签组 ${selection.tagGroupId}`,
);
}
}
const byGroup = new Map<string, bigint[]>();
for (const tag of selected) {
const key = tag.tagGroupId?.toString() ?? `tag:${tag.id.toString()}`;
for (const selection of selections) {
const key = selection.tagGroupId;
const ids = byGroup.get(key) ?? [];
if (!ids.some((id) => id === tag.id)) ids.push(tag.id);
const id = BigInt(selection.tagId);
if (!ids.includes(id)) ids.push(id);
byGroup.set(key, ids);
}
return [...byGroup.values()].map((ids) => ({