summaryrefslogtreecommitdiff
path: root/app/lib/api/odooApi.ts
blob: f1721587f8da12b47a8b648f5f95d46d74a0887a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import axios from "axios";
import { getCookie, setCookie } from "cookies-next";
import { getAuth } from "./auth";

type MethodType = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD";
type HeaderMap = Record<string, string>;
type PayloadMap = Record<string, string>;

interface AxiosParameters {
  method: MethodType;
  url: string;
  headers: HeaderMap;
  data?: string;
}

interface AuthPayload {
  token?: string;
  email?: string;
  // properti lain biarkan unknown
  [key: string]: unknown;
}

const renewToken = async (): Promise<string> => {
  const token = await axios.get(
    `${process.env.NEXT_PUBLIC_ODOO_API_HOST}/api/token`
  );
  setCookie("token", token.data.result);
  return token.data.result as string;
};

const getToken = async (): Promise<string> => {
  let token = getCookie("token") as string | undefined;
  if (token == null) token = await renewToken();
  return token;
};

const odooApi = async (
  method: MethodType,
  url: string,
  data: PayloadMap = {},
  headers: HeaderMap = {}
) => {
  try {
    const bearer = await getToken();
    const authObj = getAuth() as AuthPayload | string | null;

    const axiosParameter: AxiosParameters = {
      method,
      url: `${process.env.NEXT_PUBLIC_ODOO_API_HOST}${url}`,
      headers: { Authorization: bearer ?? "", ...headers },
    };

    // pasang header Token bila ada
    if (authObj && typeof authObj === "object" && "token" in authObj) {
      const t = authObj.token;
      if (typeof t === "string" && t) {
        axiosParameter.headers["Token"] = t;
      }
    }

    const upper = method.toUpperCase() as MethodType;

    // Body methods
    if (upper === "POST" || upper === "PUT" || upper === "PATCH") {
      axiosParameter.headers["Content-Type"] =
        "application/x-www-form-urlencoded";
    }

    // hanya kirim body untuk method yang pakai body
    if (
      Object.keys(data).length > 0 &&
      upper !== "GET" &&
      upper !== "HEAD"
    ) {
      // filter undefined/null/'' agar field opsional tidak terkirim
      const entries = Object.entries(data).filter(
        ([, v]) => typeof v === "string" && v !== ""
      ) as [string, string][];
      axiosParameter.data = new URLSearchParams(entries).toString();
    }

    const response = await axios(axiosParameter);
    return response.data as unknown;
  } catch (error) {
    console.log(JSON.stringify(error));
    throw error;
  }
};

export default odooApi;