Return 0 for wordsCount if error

This commit is contained in:
Hongbo Wu 2022-09-06 17:21:07 +08:00
parent 33f53da7f0
commit d4dcec75d5
3 changed files with 13 additions and 7 deletions

View file

@ -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,
})

View file

@ -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

View file

@ -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<void> => {
setTimeout(resolve, ms)
})
}
export const wordsCount = (text: string, isHtml = true): number => {
try {
return wordsCounter(text, { isHtml }).wordsCount
} catch {
return 0
}
}