Fakultas Ilmu Komputer UI

api.ts 1.43 KB
Newer Older
1
import axios, { AxiosRequestConfig } from 'axios';
Wulan Mantiri's avatar
Wulan Mantiri committed
2
import { API_BASE_URL } from 'env';
3
4
5
6
7

export enum RequestMethod {
  GET = 'GET',
  POST = 'POST',
  PUT = 'PUT',
8
  PATCH = 'PATCH',
9
10
11
  DELETE = 'DELETE',
}

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

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

20
const apiInstance = axios.create({
21
  baseURL: API_BASE_URL + '/',
22
23
});

24
export async function api<T>(
25
26
27
28
  method: RequestMethod = RequestMethod.GET,
  url: string,
  body: object = {},
  headers: object = {},
29
): ApiResponse<T> {
30
  const requestData: AxiosRequestConfig = {
31
    url,
32
33
    method,
    data: JSON.stringify(body),
34
35
36
37
38
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json;charset=UTF-8',
      ...headers,
    },
39
40
  };

41
  return await apiInstance
42
43
44
45
46
47
48
    .request(requestData)
    .then((res) => ({
      success: true,
      data: res.data,
    }))
    .catch((err) => ({
      success: false,
49
      error: err.response.data,
50
51
    }));
}
52
53
54
55
56
57
58
59
60
61

export const setAuthHeader = (token: string): void => {
  apiInstance.defaults.headers.Authorization = `Bearer ${token}`;
};

export const resetAuthHeader = (): void => {
  apiInstance.defaults.headers.Authorization = '';
};

export const set401Callback = (callback: () => void): void => {
62
63
  apiInstance.interceptors.response.use(undefined, (err) => {
    if (err.response.status === 401) {
64
65
      callback();
    }
66
    return Promise.reject(err);
67
68
  });
};