123456789101112131415161718192021222324252627282930313233343536 |
- import queryString from 'query-string';
- import config from '../config';
- type Props = {
- path: string;
- method: 'GET' | 'POST' | 'PUT' | 'DELETE';
- data?: Record<string, unknown>;
- };
- const invokeApi = ({ path, method, data }: Props): Promise<unknown> => {
- let stringified = '';
- const options: Record<string, unknown> = {
- 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 }));
- };
- export default invokeApi;
|