diff --git a/packages/api/src/elastic/pages.ts b/packages/api/src/elastic/pages.ts index a240a42e1..8bc811a04 100644 --- a/packages/api/src/elastic/pages.ts +++ b/packages/api/src/elastic/pages.ts @@ -22,7 +22,7 @@ import { import { client, INDEX_ALIAS } from './index' import { EntityType } from '../datalayer/pubsub' import { ResponseError } from '@elastic/elasticsearch/lib/errors' -import wordsCounter from 'word-counting' +import { wordsCount } from '../utils/helpers' const appendQuery = (body: SearchBody, query: string): void => { body.query.bool.should.push({ @@ -191,7 +191,7 @@ export const createPage = async ( ...page, updatedAt: new Date(), savedAt: new Date(), - wordsCount: wordsCounter(page.content, { isHtml: true }).wordsCount, + wordsCount: wordsCount(page.content), }, refresh: ctx.refresh, }) diff --git a/packages/api/src/resolvers/article/index.ts b/packages/api/src/resolvers/article/index.ts index 82fae81e8..e3ab899b0 100644 --- a/packages/api/src/resolvers/article/index.ts +++ b/packages/api/src/resolvers/article/index.ts @@ -60,6 +60,7 @@ import { titleForFilePath, userDataToUser, validatedDate, + wordsCount, } from '../../utils/helpers' import { ParsedContentPuppeteer, @@ -94,7 +95,6 @@ import { updatePage, } from '../../elastic/pages' import { searchHighlights } from '../../elastic/highlights' -import wordsCounter from 'word-counting' export type PartialArticle = Omit< Article, @@ -258,9 +258,6 @@ export const createArticleResolver = authorized< const saveTime = new Date() const slug = generateSlug(parsedContent?.title || croppedPathname) - const wordsCount = wordsCounter(parsedContent?.content || '', { - isHtml: true, - }).wordsCount const articleToSave: Page = { id: pageId || '', userId: uid, @@ -293,7 +290,7 @@ export const createArticleResolver = authorized< readingProgressAnchorIndex: 0, state: ArticleSavingRequestStatus.Succeeded, language: parsedContent?.language, - wordsCount, + wordsCount: wordsCount(parsedContent?.textContent || ''), } let archive = false diff --git a/packages/api/src/utils/helpers.ts b/packages/api/src/utils/helpers.ts index 98a9de742..c85903660 100644 --- a/packages/api/src/utils/helpers.ts +++ b/packages/api/src/utils/helpers.ts @@ -16,6 +16,7 @@ import { ArticleSavingRequestStatus, Page } from '../elastic/types' import { updatePage } from '../elastic/pages' import path from 'path' import normalizeUrl from 'normalize-url' +import wordsCounter from 'word-counting' interface InputObject { // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -260,3 +261,11 @@ export const wait = (ms: number): Promise => { setTimeout(resolve, ms) }) } + +export const wordsCount = (text: string, isHtml = true): number => { + try { + return wordsCounter(text, { isHtml }).wordsCount + } catch { + return 0 + } +}