import fetch from 'isomorphic-unfetch';
import queryString from 'query-string';
import config from '../config';

type Props = {
  path: string;
  method: 'GET' | 'POST' | 'PUT' | 'DELETE';
  data: Record<string, any>;
};

export default ({ path, method, data }: Props): Promise<any> => {
  let stringified = '';
  const options: any = {
    method,
    headers: {
      Accept: 'application/json',
      'Content-type': 'application/json',
    },
  };

  if (data) {
    if (method === 'GET') {
      stringified = queryString.stringify(data);
    } else {
      options.body = JSON.stringify(data);
    }
  }

  const apiHost = config.API_HOST;

  return fetch(`${apiHost}${path}?${stringified}`, options)
    .then(res => res.json())
    .catch(error => ({ error: true, message: error.message }));
};
