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
|
import axios from 'axios';
import camelcaseObjectDeep from 'camelcase-object-deep';
import { getCookie, setCookie } from 'cookies-next';
import { deleteAuth, getAuth } from '../utils/auth';
const renewToken = async () => {
let token = await axios.get(
process.env.NEXT_PUBLIC_ODOO_API_HOST + '/api/token'
);
setCookie('token', token.data.result);
return token.data.result;
};
const getToken = async () => {
let token = getCookie('token');
if (token == undefined) token = await renewToken();
return token;
};
const maxConnectionAttempt = 15;
let connectionAttempt = 0;
/**
* The `odooApi` function is used to make API requests to an Odoo backend with customizable parameters such as `method`, `url`, `data`, and `headers`.
*
* @async
* @function
* @param {string} method - HTTP method for the API request (e.g., GET, POST, PUT, DELETE).
* @param {string} url - URL endpoint for the API request.
* @param {Object} data - Data to be sent in the request payload.
* @param {Object} headers - Custom headers to be sent in the request.
* @returns {Promise} - A Promise that resolves to the API response data or an empty array.
*/
const odooApi = async (method, url, data = {}, headers = {}) => {
connectionAttempt++;
try {
let token = await getToken();
const auth = getAuth();
let axiosParameter = {
method,
url: process.env.NEXT_PUBLIC_ODOO_API_HOST + url,
headers: { Authorization: token, ...headers },
};
if (auth) {
axiosParameter.headers['Token'] = auth.token;
}
// Tentukan format data berdasarkan metode dan data
if (Object.keys(data).length > 0) {
if (method.toUpperCase() === 'POST') {
// Gunakan URL-encoded untuk POST
axiosParameter.data = new URLSearchParams(
Object.entries(data)
).toString();
axiosParameter.headers['Content-Type'] =
'application/x-www-form-urlencoded';
} else {
// Gunakan JSON untuk GET/PUT atau metode lainnya
axiosParameter.data = data;
axiosParameter.headers['Content-Type'] = 'application/json';
}
}
let res = await axios(axiosParameter);
if (res.data?.status?.code === 401) {
if (connectionAttempt < maxConnectionAttempt) {
await renewToken();
return odooApi(method, url, data, headers);
} else {
await deleteAuth();
window.location.href = '/login';
return false;
}
}
return camelcaseObjectDeep(res.data.result) || [];
} catch (error) {
console.error('API Error:', error);
throw error; // Opsional, lempar error agar bisa ditangkap di level atas
}
};
export default odooApi;
|