Created
October 10, 2019 07:28
-
-
Save cfitz/6d8fdf01b793ffe316cc9c1941cc8ba6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Fq from './fq' | |
import { SolrQueryOptions } from '../../types/types' | |
import SolrParams from './solrParams' | |
class SolrQuery { | |
// Filters | |
fqs: Fq[] | |
// Query | |
q: string | |
// Everything Else | |
params: SolrParams | |
constructor({ | |
fqs = [], | |
params = new SolrParams(), | |
q = '', | |
}: SolrQueryOptions = {}) { | |
this.fqs = fqs | |
this.params = params | |
this.q = q | |
} | |
fq(field: string, values: string[]): SolrQuery { | |
this.fqs.push(new Fq(field, values)) | |
return this | |
} | |
fqNot(field: string, values: string[]): SolrQuery { | |
this.fqs.push(new Fq(`-${field}`, values)) | |
return this | |
} | |
set(name: string, value: string): SolrQuery { | |
this.params.set(name, value) | |
return this | |
} | |
rows(count: number): SolrQuery { | |
this.params.set('rows', count.toString()) | |
return this | |
} | |
start(count: number): SolrQuery { | |
this.params.set('start', count.toString()) | |
return this | |
} | |
q(query: string): SolrQuery { | |
this.set('q', query) | |
return this | |
} | |
facetFields(facets: string[]): SolrQuery { | |
this.params.facetFields(facets) | |
return this | |
} | |
toQueryParams(): URLSearchParams { | |
const queryParams = new URLSearchParams() | |
const { fqs, params, q } = this | |
const fqParams = fqs | |
.map(f => f.toParam()) | |
.filter(params => params.length > 0) | |
.join(' AND ') | |
if (fqParams.length > 0) { | |
queryParams.set('fq', fqParams) | |
} | |
// Solr is funny. it doesnt like the standard object params | |
// ( i.e. "facet.field[]=cat&facet.field[]=dog") | |
// params that are arrays are just listed multiple times, | |
// ( i.e. "facet.field=cat&facet.field=dog" ) | |
// In this case, we need to use .append instead of just passing | |
// an array. | |
params.forEach((value: string | string[], key: string) => { | |
if (Array.isArray(value)) { | |
value.forEach(val => queryParams.append(key, val)) | |
} else { | |
queryParams.set(key, value) | |
} | |
}) | |
return queryParams | |
} | |
} | |
export default SolrQuery |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment