apiHelpers.ts 800 B

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