import axios, { AxiosRequestConfig, Method } from 'axios'; import { getCookie, setCookie } from 'cookies-next'; import { getAuth } from './auth'; import { AuthApiProps } from '~/types/auth'; const ODOO_HOST = process.env.NEXT_PUBLIC_ODOO_API_HOST as string; const renewToken = async () => { let token = await axios.get(`${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: Method, url: string, data = {}, headers = {} ): Promise => { connectionAttempt++; try { let token = await getToken(); const auth = getAuth(); let axiosParameter: AxiosRequestConfig = { method, url: process.env.NEXT_PUBLIC_ODOO_API_HOST + url, headers: { Authorization: token, ...headers }, }; if (typeof auth === 'object' && 'token' in auth) { axiosParameter.headers = { ...axiosParameter.headers, Token: auth.token, }; } if (method.toUpperCase() === 'POST') { axiosParameter.headers = { ...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); const authResponse: AuthApiProps = res.data; if ( authResponse.status.code == 401 && connectionAttempt < maxConnectionAttempt ) { await renewToken(); return odooApi(method, url, data, headers); } return authResponse.result || null; } catch (error) { console.log(error); return null; } }; export default odooApi;