add label to page only if not exists

This commit is contained in:
Hongbo Wu 2022-03-16 23:00:37 +08:00
parent 1c4dcd7b00
commit 07dcd5da26
2 changed files with 35 additions and 8 deletions

View file

@ -19,6 +19,7 @@ import {
} from './types'
import { readFileSync } from 'fs'
import { join } from 'path'
import { Label } from '../entity/label'
const INDEX_NAME = 'pages'
const INDEX_ALIAS = 'pages_alias'
@ -207,6 +208,38 @@ export const updatePage = async (
}
}
export const addLabelInPage = async (
id: string,
label: Label,
ctx: PageContext
): Promise<boolean> => {
try {
const { body } = await client.update({
index: INDEX_ALIAS,
id,
body: {
script: {
source:
'if (!ctx._source.labels.contains(params.label)) { ctx._source.labels.add(label) }',
lang: 'painless',
params: {
label: label,
},
},
doc: {
updatedAt: new Date(),
},
},
refresh: ctx.refresh,
})
return body.result === 'updated'
} catch (e) {
console.error('failed to update a page in elastic', e)
return false
}
}
export const deletePage = async (
id: string,
ctx: PageContext

View file

@ -2,9 +2,9 @@ import DataLoader from 'dataloader'
import { Label } from '../entity/label'
import { getRepository, ILike, In } from 'typeorm'
import { Link } from '../entity/link'
import { updatePage } from '../elastic'
import { PageContext } from '../elastic/types'
import { User } from '../entity/user'
import { addLabelInPage } from '../elastic'
const batchGetLabelsFromLinkIds = async (
linkIds: readonly string[]
@ -50,11 +50,5 @@ export const addLabelToPage = async (
console.log('adding label to page', label.name, pageId)
return updatePage(
pageId,
{
labels: [labelEntity],
},
ctx
)
return addLabelInPage(pageId, labelEntity, ctx)
}