summaryrefslogtreecommitdiff
path: root/src-migrate/libs/odooApi.ts
diff options
context:
space:
mode:
authorIT Fixcomart <it@fixcomart.co.id>2024-01-19 02:32:43 +0000
committerIT Fixcomart <it@fixcomart.co.id>2024-01-19 02:32:43 +0000
commit8bcadf6d43a44169c422305522784424c30c7b02 (patch)
tree4666802b65784a949db4acad665a81de7297fc74 /src-migrate/libs/odooApi.ts
parent065396828266e2de42cb0182c81ea2d7a5b00e2b (diff)
parent91086d8b1af2e1c0ca9db38d037f6331c9e6131a (diff)
Merged in Feature/perf/product-detail (pull request #127)
Feature/perf/product detail
Diffstat (limited to 'src-migrate/libs/odooApi.ts')
-rw-r--r--src-migrate/libs/odooApi.ts81
1 files changed, 81 insertions, 0 deletions
diff --git a/src-migrate/libs/odooApi.ts b/src-migrate/libs/odooApi.ts
new file mode 100644
index 00000000..9482542b
--- /dev/null
+++ b/src-migrate/libs/odooApi.ts
@@ -0,0 +1,81 @@
+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<any> => {
+ 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;