2016-09-20 13:42:08 +00:00
|
|
|
import fetch from 'isomorphic-fetch';
|
|
|
|
|
2016-09-16 13:55:46 +00:00
|
|
|
import config from '../config';
|
2016-09-19 23:43:35 +00:00
|
|
|
import local from '../utilities/local';
|
2016-09-16 13:55:46 +00:00
|
|
|
|
|
|
|
class Base {
|
|
|
|
constructor () {
|
|
|
|
this.baseURL = this.setBaseURL();
|
2016-09-19 23:43:35 +00:00
|
|
|
this.bearerToken = local.getItem('auth_token');
|
2016-09-16 13:55:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
setBaseURL () {
|
|
|
|
const {
|
|
|
|
settings: { env },
|
|
|
|
environments: { development },
|
|
|
|
} = config;
|
|
|
|
|
|
|
|
if (env === development) {
|
|
|
|
return 'http://localhost:8080/api';
|
|
|
|
}
|
|
|
|
|
|
|
|
throw new Error(`API base URL is not configured for environment: ${env}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
setBearerToken (bearerToken) {
|
|
|
|
this.bearerToken = bearerToken;
|
|
|
|
}
|
|
|
|
|
2016-09-19 23:43:35 +00:00
|
|
|
authenticatedGet (endpoint, overrideHeaders = {}) {
|
|
|
|
return this._authenticatedRequest('GET', endpoint, {}, overrideHeaders);
|
|
|
|
}
|
|
|
|
|
|
|
|
authenticatedPost (endpoint, body = {}, overrideHeaders = {}) {
|
|
|
|
return this._authenticatedRequest('POST', endpoint, body, overrideHeaders);
|
|
|
|
}
|
|
|
|
|
|
|
|
post (endpoint, body = {}, overrideHeaders = {}) {
|
2016-09-16 13:55:46 +00:00
|
|
|
return this._request('POST', endpoint, body, overrideHeaders);
|
|
|
|
}
|
|
|
|
|
2016-09-19 23:43:35 +00:00
|
|
|
_authenticatedRequest(method, endpoint, body, overrideHeaders) {
|
|
|
|
const headers = {
|
|
|
|
...overrideHeaders,
|
|
|
|
Authorization: `Bearer ${this.bearerToken}`,
|
2016-09-20 13:42:08 +00:00
|
|
|
};
|
2016-09-19 23:43:35 +00:00
|
|
|
|
|
|
|
return this._request(method, endpoint, body, headers);
|
|
|
|
}
|
|
|
|
|
2016-09-16 13:55:46 +00:00
|
|
|
_request (method, endpoint, body, overrideHeaders) {
|
|
|
|
const headers = {
|
|
|
|
Accept: 'application/json',
|
|
|
|
'Content-Type': 'application/json',
|
2016-09-19 23:43:35 +00:00
|
|
|
...overrideHeaders,
|
2016-09-16 13:55:46 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
return fetch(endpoint, {
|
|
|
|
method,
|
2016-09-19 23:43:35 +00:00
|
|
|
headers,
|
2016-09-16 13:55:46 +00:00
|
|
|
body,
|
|
|
|
})
|
|
|
|
.then(response => {
|
|
|
|
return response.json()
|
|
|
|
.then(jsonResponse => {
|
|
|
|
if (response.ok) {
|
|
|
|
return jsonResponse;
|
|
|
|
}
|
|
|
|
|
|
|
|
const error = new Error(response.statusText);
|
|
|
|
error.response = jsonResponse;
|
|
|
|
error.message = jsonResponse;
|
|
|
|
error.error = jsonResponse.error;
|
|
|
|
|
|
|
|
throw error;
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default Base;
|
|
|
|
|