From 754aa9e4963511be586325bd36b01febf6974edb Mon Sep 17 00:00:00 2001 From: ditiqi Date: Wed, 26 Feb 2025 17:04:20 +0800 Subject: [PATCH] add --- apps/server/src/queue/models/post/utils.ts | 90 ++++++++++++---------- 1 file changed, 51 insertions(+), 39 deletions(-) diff --git a/apps/server/src/queue/models/post/utils.ts b/apps/server/src/queue/models/post/utils.ts index 690a3b0..51d2b04 100644 --- a/apps/server/src/queue/models/post/utils.ts +++ b/apps/server/src/queue/models/post/utils.ts @@ -64,9 +64,50 @@ export async function updateTotalCourseViewCount(type: VisitType) { export async function updatePostViewCount(id: string, type: VisitType) { const post = await db.post.findFirst({ where: { id }, - select: { id: true, meta: true }, + select: { id: true, meta: true, type: true }, }); - + const metaFieldMap = { + [VisitType.READED]: 'views', + [VisitType.LIKE]: 'likes', + [VisitType.HATE]: 'hates', + }; + if (post?.type === PostType.LECTURE) { + const course = await db.postAncestry.findFirst({ + where: { + descendantId: post?.id, + ancestor: { + type: PostType.COURSE, + }, + }, + select: { id: true }, + }); + const lectures = await db.postAncestry.findMany({ + where: { ancestorId: course.id, descendant: { type: PostType.LECTURE } }, + select: { + id: true, + }, + }); + const courseViews = await db.visit.aggregate({ + _sum: { + views: true, + }, + where: { + postId: { + in: [course.id, ...lectures.map((lecture) => lecture.id)], + }, + type: type, + }, + }); + await db.post.update({ + where: { id: course.id }, + data: { + meta: { + ...((post?.meta as any) || {}), + [metaFieldMap[type]]: courseViews._sum.views || 0, + }, + }, + }); + } const totalViews = await db.visit.aggregate({ _sum: { views: true, @@ -76,42 +117,13 @@ export async function updatePostViewCount(id: string, type: VisitType) { type: type, }, }); - if (type === VisitType.READED) { - await db.post.update({ - where: { - id: id, + await db.post.update({ + where: { id }, + data: { + meta: { + ...((post?.meta as any) || {}), + [metaFieldMap[type]]: totalViews._sum.views || 0, }, - data: { - meta: { - ...((post?.meta as any) || {}), - views: totalViews._sum.views || 0, - }, // Use 0 if no visits exist - }, - }); - console.log('readed'); - } else if (type === VisitType.LIKE) { - await db.post.update({ - where: { - id: id, - }, - data: { - meta: { - ...((post?.meta as any) || {}), - likes: totalViews._sum.views || 0, // Use 0 if no visits exist - }, - }, - }); - } else if (type === VisitType.HATE) { - await db.post.update({ - where: { - id: id, - }, - data: { - meta: { - ...((post?.meta as any) || {}), - hates: totalViews._sum.views || 0, // Use 0 if no visits exist - }, - }, - }); - } + }, + }); }