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
|
import axios from "axios"
import { getCookie, setCookie } from "cookies-next";
import { getAuth } from "./auth";
type axiosParameters = {
method : string,
url : string,
headers : {
Authorization : string,
'Content-Type'? : string,
Token? : string
},
data ?: string
}
const renewToken = async () => {
const 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 odooApi = async (method: string, url: string, data = {}, headers = {}) => {
try {
const token = await getToken();
const auth = getAuth();
const axiosParameter: axiosParameters = {
method,
url: process.env.NEXT_PUBLIC_ODOO_API_HOST + url,
headers: { Authorization: token ? token : '', ...headers },
};
if (auth && typeof auth === 'object' && 'token' in auth) {
axiosParameter.headers['Token'] = (auth as any).token;
}
const upper = method.toUpperCase();
// Set Content-Type untuk method yang kirim body
if (upper === 'POST' || upper === 'PUT' || upper === 'PATCH') {
axiosParameter.headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
// Hanya kirim body untuk method yang memang pakai body
if (Object.keys(data).length > 0 && upper !== 'GET' && upper !== 'HEAD') {
const entries = Object.entries(data).filter(
([, v]) => v !== undefined && v !== null && v !== ''
) as [string, string][];
axiosParameter.data = new URLSearchParams(entries).toString();
}
const response = await axios(axiosParameter);
return response.data;
} catch (error) {
console.log(JSON.stringify(error));
}
};
export default odooApi
|