From 07dcd5da26492298b5f4b73c6f256cf3059196ec Mon Sep 17 00:00:00 2001 From: Hongbo Wu Date: Wed, 16 Mar 2022 23:00:37 +0800 Subject: [PATCH] add label to page only if not exists --- packages/api/src/elastic/index.ts | 33 +++++++++++++++++++++++++++++ packages/api/src/services/labels.ts | 10 ++------- 2 files changed, 35 insertions(+), 8 deletions(-) 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) }