Recommend highlights

This commit is contained in:
Hongbo Wu 2022-12-08 12:33:05 +08:00
parent 62a3f6d1d8
commit ef13cbf39a
2 changed files with 33 additions and 9 deletions

View file

@ -4,28 +4,50 @@ import { createPage, getPageByParam, updatePage } from './pages'
export const addRecommendation = async (
ctx: PageContext,
page: Page,
recommendation: Recommendation
recommendation: Recommendation,
highlightIds?: string[]
): Promise<string | undefined> => {
try {
const highlights = page.highlights?.filter((highlight) =>
highlightIds?.includes(highlight.id)
)
// check if the page is already recommended to the group
const existingPage = await getPageByParam({
userId: ctx.uid,
url: page.url,
})
if (existingPage) {
if (existingPage.recommendations?.includes(recommendation)) {
const existingHighlights = existingPage.highlights || []
// remove duplicates
const newHighlights =
highlights?.filter(
(highlight) =>
!existingHighlights.find(
(existingHighlight) => existingHighlight.quote === highlight.quote
)
) || []
const existingRecommendations = existingPage.recommendations || []
const isRecommended = existingRecommendations.some(
(existingRecommendation) =>
existingRecommendation.id === recommendation.id
)
if (isRecommended && newHighlights.length === 0) {
return existingPage._id
}
// update recommendedBy in the existing page
const recommendations = (existingPage.recommendations || []).concat(
recommendation
)
// update recommendations in the existing page
const recommendations = isRecommended
? undefined
: existingRecommendations.concat(recommendation)
await updatePage(
existingPage.id,
{
recommendations,
highlights: existingHighlights.concat(newHighlights),
},
ctx
)
@ -41,7 +63,7 @@ export const addRecommendation = async (
readingProgressPercent: 0,
readingProgressAnchorIndex: 0,
sharedAt: new Date(),
highlights: [],
highlights,
readAt: undefined,
labels: [],
}

View file

@ -163,10 +163,11 @@ export function pageRouter() {
}
const claims = jwt.decode(token) as Claims
const { userId, pageId, recommendation } = req.body as {
const { userId, pageId, recommendation, highlightIds } = req.body as {
userId: string
pageId: string
recommendation: Recommendation
highlightIds?: string[]
}
if (!userId || !pageId || !recommendation) {
return res.status(400).send({ errorCode: 'BAD_DATA' })
@ -188,7 +189,8 @@ export function pageRouter() {
const recommendedPageId = await addRecommendation(
ctx,
page,
recommendation
recommendation,
highlightIds
)
if (!recommendedPageId) {
logger.error('Failed to add recommendation to page')