import store from '../store';

const baseUrl = () => store.getState().config.base_api_url.replace(/\/+$/g, '');
const endpoint = (path) => `${baseUrl()}/admin/${path.replace(/^\/+/g, '')}`;

const request = (method, path, data = null) => {
  return fetch(endpoint(path), {
    method: method,
    credentials: 'include',
    headers: { 'Content-Type': 'application/json' },
    body: data && JSON.stringify(data),
  }).then(response => response.json())
    .then((response) => {
      if (!!response.error) {
        throw response.error;
      }

      return response;
    });
};

export default {
  get: (path) => request('GET', path),
  post: (path, data) => request('POST', path, data),
};
