redoc/src/services/SearchWorker.worker.ts

63 lines
1.3 KiB
TypeScript
Raw Normal View History

2018-02-08 19:41:02 +03:00
import * as lunr from 'lunr';
/* just for better typings */
export default class Worker {
add = add;
done = done;
search = search;
}
export interface SearchDocument {
title: string;
description: string;
id: string;
}
2018-02-22 19:48:50 +03:00
export interface SearchResult extends SearchDocument {
score: number;
}
2018-02-08 19:41:02 +03:00
const store: { [id: string]: SearchDocument } = {};
let resolveIndex: (v: lunr.Index) => void;
const index: Promise<lunr.Index> = new Promise(resolve => {
resolveIndex = resolve;
});
const builder = new lunr.Builder();
builder.field('title');
builder.field('description');
builder.ref('id');
builder.pipeline.add(lunr.trimmer, lunr.stopWordFilter, lunr.stemmer);
const expandTerm = term => '*' + lunr.stemmer(new lunr.Token(term, {})) + '*';
export function add(title: string, description: string, id: string) {
const item = { title, description, id };
builder.add(item);
store[id] = item;
}
export async function done() {
resolveIndex(builder.build());
}
2018-02-22 19:48:50 +03:00
export async function search(q: string): Promise<SearchResult[]> {
2018-02-08 19:41:02 +03:00
if (q.trim().length === 0) {
return [];
}
return (await index)
.query(t => {
q
.trim()
.split(/\s+/)
.forEach(term => {
const exp = expandTerm(term);
t.term(exp, {});
});
})
2018-02-22 19:48:50 +03:00
.map(res => ({ ...store[res.ref], score: res.score }));
2018-02-08 19:41:02 +03:00
}