@brettvormkopp Bzgl. deiner Abfrage auf Basis eines Objekts. Habe da meine Class noch etwas überarbeitet. Ist jetzt aber nur für Filter.
export default class Api {
constructor() {
this.host = process.env.REACT_APP_API_URL;
this.apiKey = process.env.REACT_APP_API_KEY;
}
async handleRequest(selector) {
return fetch(this.host + selector.url, {
method: selector.method,
headers: {
"x-sw-access-key": this.apiKey,
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(json => json)
.catch(error => console.error(error));
}
handleFilters(entityName, params) {
const entity = entityName.replace("/", "");
const filter = [];
for (const key in params) {
if (params.hasOwnProperty(key)) {
const url = `filter[${entity}.${key}]=${params[key]}`;
filter.push(url);
}
}
const result = "?" + filter.join("&");
return result;
}
getResult(entityName, params) {
let url = "";
if (params !== undefined) {
url = `${entityName}${this.handleFilters(entityName, params)}`;
} else {
url = `${entityName}`;
}
return this.handleRequest({
url,
method: "GET"
});
}
}
Den Request machste dann bspw. mit:
await this.shop.getResult("product/", {
categoryTree: this.props.match.params.categoryId,
weitererFilter: value,
});