|
| 1 | +import { Store } from './index.js'; |
| 2 | + |
| 3 | +export interface SearchOpts { |
| 4 | + /** Fetch full resources instead of subjects */ |
| 5 | + include?: boolean; |
| 6 | + /** Max of how many results to return */ |
| 7 | + limit?: number; |
| 8 | + /** Subject of resource to scope the search to. This should be a parent of the resources you're looking for. */ |
| 9 | + scope?: string; |
| 10 | + /** Property-Value pair of set filters. For now, use the `shortname` of the property as the key. */ |
| 11 | + filters?: { |
| 12 | + [propertyShortname: string]: string; |
| 13 | + }; |
| 14 | +} |
| 15 | + |
| 16 | +// https://github.com/quickwit-oss/tantivy/blob/064518156f570ee2aa03cf63be6d5605a96d6285/query-grammar/src/query_grammar.rs#L19 |
| 17 | +const specialCharsTantivy = [ |
| 18 | + '+', |
| 19 | + '^', |
| 20 | + '`', |
| 21 | + ':', |
| 22 | + '{', |
| 23 | + '}', |
| 24 | + '"', |
| 25 | + '[', |
| 26 | + ']', |
| 27 | + '(', |
| 28 | + ')', |
| 29 | + '!', |
| 30 | + '\\', |
| 31 | + '*', |
| 32 | + ' ', |
| 33 | + // The dot is escaped, even though it's not in Tantivy's list. |
| 34 | + '.', |
| 35 | +]; |
| 36 | + |
| 37 | +/** escape the key conform to Tantivy syntax, escaping all specialCharsTantivy */ |
| 38 | +export function escapeTantivyKey(key: string) { |
| 39 | + return key.replace( |
| 40 | + new RegExp(`([${specialCharsTantivy.join('\\')}])`, 'g'), |
| 41 | + '\\$1', |
| 42 | + ); |
| 43 | +} |
| 44 | + |
| 45 | +/** Uses Tantivy query syntax */ |
| 46 | +function buildFilterString(filters: { [key: string]: string }): string { |
| 47 | + return Object.entries(filters) |
| 48 | + .map(([key, value]) => { |
| 49 | + return value && value.length > 0 && `${escapeTantivyKey(key)}:"${value}"`; |
| 50 | + }) |
| 51 | + .join(' AND '); |
| 52 | +} |
| 53 | + |
| 54 | +/** Returns the URL of the search query. Fetch that and you get your results! */ |
| 55 | +export function buildSearchSubject( |
| 56 | + store: Store, |
| 57 | + query: string, |
| 58 | + opts: SearchOpts = {}, |
| 59 | +) { |
| 60 | + const { include = false, limit = 30, scope, filters } = opts; |
| 61 | + const url = new URL(store.getServerUrl()); |
| 62 | + url.pathname = 'search'; |
| 63 | + query && url.searchParams.set('q', query); |
| 64 | + include && url.searchParams.set('include', include.toString()); |
| 65 | + limit && url.searchParams.set('limit', limit.toString()); |
| 66 | + // Only add filters if there are any keys, and if any key is defined |
| 67 | + const hasFilters = |
| 68 | + filters && |
| 69 | + Object.keys(filters).length > 0 && |
| 70 | + Object.values(filters).filter(v => v && v.length > 0).length > 0; |
| 71 | + hasFilters && url.searchParams.set('filters', buildFilterString(filters)); |
| 72 | + |
| 73 | + if (scope) { |
| 74 | + url.searchParams.set('parent', scope); |
| 75 | + } |
| 76 | + |
| 77 | + return url.toString(); |
| 78 | +} |
0 commit comments