blob: 41460fda81c8003ceda4228f99f5bf688a98d72d (
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
|
import axios from 'axios'
import camelcaseObjectDeep from 'camelcase-object-deep'
import { getCookie, setCookie } from 'cookies-next'
import { getAuth } from '../utils/auth'
const renewToken = async () => {
let token = await axios.get(process.env.NEXT_PUBLIC_ODOO_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
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_HOST + url,
headers: { Authorization: token, ...headers }
}
if (auth) axiosParameter.headers['Token'] = auth.token
if (method.toUpperCase() == 'POST')
axiosParameter.headers['Content-Type'] = 'application/x-www-form-urlencoded'
if (Object.keys(data).length > 0)
axiosParameter.data = new URLSearchParams(Object.entries(data)).toString()
let res = await axios(axiosParameter)
if (res.data.status.code == 401 && connectionAttempt < maxConnectionAttempt) {
await renewToken()
return odooApi(method, url, data, headers)
}
return camelcaseObjectDeep(res.data.result) || []
} catch (error) {
console.log(error)
}
}
export default odooApi
|