Fakultas Ilmu Komputer UI

api.ts 1.4 KB
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
export interface Response<T> {
  success: boolean;
  data?: T;
  error?: any;
}

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

18
19
20
21
const apiInstance = axios.create({
  baseURL: 'https://dietela-backend.herokuapp.com/',
});

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

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

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 => {
  apiInstance.interceptors.response.use(undefined, (response) => {
    if (response.status === 401) {
      callback();
    }
    return Promise.reject(response);
  });
};