Catch errors in search worker

This commit is contained in:
squidfunk 2019-12-20 10:24:06 +01:00
parent 2fa347aaae
commit b31061dbeb

View File

@ -181,48 +181,50 @@ export class Search {
* page. For this reason, section results are grouped within their respective * page. For this reason, section results are grouped within their respective
* articles which are the top-level results that are returned. * articles which are the top-level results that are returned.
* *
* Rogue control characters must be filtered before handing the query to the
* search index, as lunr will throw otherwise.
*
* @param query - Query string * @param query - Query string
* *
* @return Search results * @return Search results
*/ */
public search(query: string): SearchResult[] { public search(query: string): SearchResult[] {
query = query if (query) {
.replace(/(?:^|\s+)[*+-:^~]+(?=\s+|$)/g, "") try {
.trim()
/* Abort early, if query is empty */ /* Group sections by containing article */
if (!query) const groups = this.index.search(query)
return [] .reduce((results, result) => {
const document = this.documents.get(result.ref)
if (typeof document !== "undefined") {
if ("article" in document) {
const ref = document.article.location
results.set(ref, [...results.get(ref) || [], result])
} else {
const ref = document.location
results.set(ref, results.get(ref) || [])
}
}
return results
}, new Map<string, lunr.Index.Result[]>())
/* Group sections by containing article */ /* Create highlighter for query */
const groups = this.index.search(query) const fn = this.highlight(query)
.reduce((results, result) => {
const document = this.documents.get(result.ref)
if (typeof document !== "undefined") {
if ("article" in document) {
const ref = document.article.location
results.set(ref, [...results.get(ref) || [], result])
} else {
const ref = document.location
results.set(ref, results.get(ref) || [])
}
}
return results
}, new Map<string, lunr.Index.Result[]>())
/* Create highlighter for query */ /* Map groups to search documents */
const fn = this.highlight(query) return [...groups].map(([ref, sections]) => ({
article: fn(this.documents.get(ref) as ArticleDocument),
sections: sections.map(section => {
return fn(this.documents.get(section.ref) as SectionDocument)
})
}))
/* Map groups to search documents */ /* Log errors to console (for now) */
return [...groups].map(([ref, sections]) => ({ } catch (err) {
article: fn(this.documents.get(ref) as ArticleDocument), // tslint:disable-next-line no-console
sections: sections.map(section => { console.warn(`Invalid query: ${query} see https://bit.ly/2s3ChXG`)
return fn(this.documents.get(section.ref) as SectionDocument) }
}) }
}))
/* Return nothing in case of error or empty query */
return []
} }
/** /**