Fakultas Ilmu Komputer UI

api.ts 1.41 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
8
9
10

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

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>>;

19
const apiInstance = axios.create({
Wulan Mantiri's avatar
Wulan Mantiri committed
20
  baseURL: API_BASE_URL,
21
22
});

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

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

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 => {
61
62
  apiInstance.interceptors.response.use(undefined, (err) => {
    if (err.response.status === 401) {
63
64
      callback();
    }
65
    return Promise.reject(err);
66
67
  });
};