I have an issue, where I am not able to add additional search query fields in the request url.
I have a function, that is supposed to get career offers from the CMS, in the code below:
getCareerOffers() {
return this.getItems<CareerOffer>('career_offers', ['*', 'image.*', 'content_side_image.*']);
}
After reading Directus docs, there is a possibility to add an additional query field, to be more specific, in the form of adding [comparator][eq]
field, which would look like this:
getCareerOffers() {
return this.getItems<CareerOffer>('career_offers', ['*', 'image.*', 'content_side_image.*'], {
'[company][eq]': 'company',
});
}
The issue I am facing, is that I do not really know how to properly proceed. I have been advised, that I should be joining the fields within the function.
Here is how the function looks so far:
private getItems<T>(collection: string, fields?: string[], filter?: Record<string, string>): Observable<T[]> {
if (!this.cachedObservables[collection]) {
const prefixedFilters = {}
const params = {
...(fields ? { fields: fields.join() } : prefixedFilters),
filter: Object.keys(filter).reduce((filtersKey) => {
const prefixedFilterKey = `filters${filtersKey}`
prefixedFilters[prefixedFilterKey] = filter[filtersKey]
}),
};
this.cachedObservables[collection] = this.http
.get<CmsItems<T[]>>(`${this.apiUrl}/items/${collection}`, { params })
.pipe(
map(response => response.data),
publishReplay(1),
refCount(),
);
}
return this.cachedObservables[collection];
}
Now, where I am stuck is in the params
object, where I can not figure out, how to properly format the filter value.
Object.keys(filter)
returns an array with with 0: [company][eq]
inside it.
Any ideas on how to achieve it?
I was able to solve it. I was writing my array method wrong. This was the solution that I came up with:
if (!this.cachedObservables[collection]) {
const prefixedFilters = {};
Object.keys(filter).reduce((prefixedFilter, filterKey) => {
prefixedFilters[`filter${filterKey}`] = filter[filterKey];
return prefixedFilters;
}, prefixedFilters);
const params = {
...(fields && { fields: fields.join() }),
...prefixedFilters,
};
this.cachedObservables[collection] = this.http
.get<CmsItems<T[]>>(`${this.apiUrl}/items/${collection}`, { params })
.pipe(
map(response => response.data),
publishReplay(1),
refCount(),
);
}