apiHelpers.ts 810 B

1234567891011121314151617181920212223242526272829303132333435
  1. import fetch from 'isomorphic-unfetch';
  2. import queryString from 'query-string';
  3. import config from '../config';
  4. type Props = {
  5. path: string;
  6. method: 'GET' | 'POST' | 'PUT' | 'DELETE';
  7. data?: Record<string, any>;
  8. };
  9. export default ({ path, method, data }: Props): Promise<any> => {
  10. let stringified = '';
  11. const options: any = {
  12. method,
  13. headers: {
  14. Accept: 'application/json',
  15. 'Content-type': 'application/json',
  16. },
  17. };
  18. if (data) {
  19. if (method === 'GET') {
  20. stringified = `?${queryString.stringify(data)}`;
  21. } else {
  22. options.body = JSON.stringify(data);
  23. }
  24. }
  25. const apiHost = config.API_HOST;
  26. return fetch(`${apiHost}${path}${stringified}`, options)
  27. .then(res => res.json())
  28. .catch(error => ({ error: true, message: error.message }));
  29. };