75 lines
1.6 KiB
JavaScript
75 lines
1.6 KiB
JavaScript
import config from '../config';
|
|
import * as Errors from './Errors';
|
|
|
|
class Api {
|
|
constructor() {
|
|
}
|
|
|
|
baseUrl() { return config.baseApiUrl; }
|
|
|
|
url(path) {
|
|
return this.baseUrl() + path;
|
|
}
|
|
|
|
checkStatus(response) {
|
|
if (response.status >= 200 && response.status < 300) {
|
|
return response;
|
|
} else if (response.status === 404) {
|
|
throw new Errors.ApiNotFoundError(response.statusText, response);
|
|
} else {
|
|
throw new Errors.ApiServerError(response.statusText || "Unknown Server Error", response);
|
|
}
|
|
}
|
|
|
|
parseJSON(response) {
|
|
return response.json();
|
|
}
|
|
|
|
performRequest(url, method, params = {}) {
|
|
const hasBody = Object.keys(params || {}).length !== 0;
|
|
|
|
const headers = new Headers();
|
|
headers.append('Accept', 'application/json');
|
|
|
|
const opts = {
|
|
headers,
|
|
method: method
|
|
};
|
|
|
|
if (hasBody) {
|
|
headers.append('Content-Type', 'application/json');
|
|
opts.body = JSON.stringify(params);
|
|
}
|
|
|
|
return fetch(url, opts).then(this.checkStatus).then(this.parseJSON);
|
|
}
|
|
|
|
get(url, params = {}) {
|
|
|
|
const queryParams = [];
|
|
|
|
for (let key in params) {
|
|
const val = params[key];
|
|
if (Array.isArray(val)) {
|
|
for (let x of val) {
|
|
queryParams.push(encodeURIComponent(key) + "[]=" + (x === null ? '' : encodeURIComponent(x)));
|
|
}
|
|
} else {
|
|
queryParams.push(encodeURIComponent(key) + "=" + (val === null ? '' : encodeURIComponent(val)));
|
|
}
|
|
}
|
|
|
|
if (queryParams.length) {
|
|
url = url + "?" + queryParams.join("&");
|
|
}
|
|
|
|
return this.performRequest(url, "GET");
|
|
}
|
|
|
|
|
|
}
|
|
|
|
const api = new Api();
|
|
|
|
export default api;
|