Fakultas Ilmu Komputer UI

api.ts 802 Bytes
Newer Older
1
2
3
4
5
6
7
8
9
import axios, { AxiosRequestConfig } from 'axios';

export enum RequestMethod {
  GET = 'GET',
  POST = 'POST',
  PUT = 'PUT',
  DELETE = 'DELETE',
}

10
11
12
13
14
15
16
17
18
export interface Response<T> {
  success: boolean;
  data?: T;
  error?: any;
}

export type ApiResponse<T> = Promise<Response<T>>;

export async function api<T>(
19
20
21
22
  method: RequestMethod = RequestMethod.GET,
  url: string,
  body: object = {},
  headers: object = {},
23
): ApiResponse<T> {
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
  const requestData: AxiosRequestConfig = {
    url: `https://dietela-backend.herokuapp.com/${url}`,
    method,
    data: JSON.stringify(body),
    headers,
  };

  return await axios
    .request(requestData)
    .then((res) => ({
      success: true,
      data: res.data,
    }))
    .catch((err) => ({
      success: false,
      error: err.data,
    }));
}