diff --git a/packages/api/src/elastic/index.ts b/packages/api/src/elastic/index.ts index b8cabd53a..3e361039b 100644 --- a/packages/api/src/elastic/index.ts +++ b/packages/api/src/elastic/index.ts @@ -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 => { + 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 diff --git a/packages/api/src/services/labels.ts b/packages/api/src/services/labels.ts index a7f2a54c2..daf2d798a 100644 --- a/packages/api/src/services/labels.ts +++ b/packages/api/src/services/labels.ts @@ -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) }