diff options
Diffstat (limited to 'app/lib/api')
| -rw-r--r-- | app/lib/api/auth.ts | 42 | ||||
| -rw-r--r-- | app/lib/api/odooApi.ts | 56 |
2 files changed, 98 insertions, 0 deletions
diff --git a/app/lib/api/auth.ts b/app/lib/api/auth.ts new file mode 100644 index 0000000..d954dc5 --- /dev/null +++ b/app/lib/api/auth.ts @@ -0,0 +1,42 @@ +import { deleteCookie, getCookie, setCookie } from "cookies-next" + +type AuthProps = { + id: number; + parentId: number; + parentName: string; + partnerId: number; + name: string; + email: string; + phone: string; + npwp: string; + mobile: string; + external: boolean; + company: boolean; + pricelist: string | null; + token: string; + feature : { + onlyReadyStock : boolean, + soApproval : boolean + } + }; + +const getAuth = () : AuthProps | boolean => { + const auth = getCookie('auth') + + if (auth) return JSON.parse(auth) + return false + +} + +const setAuth = (user : AuthProps) : boolean => { + setCookie('auth', JSON.stringify(user)) + return true +} + + +const deleteAuth = () : boolean => { + deleteCookie('auth') + return true +} + +export { getAuth , setAuth, deleteAuth}
\ No newline at end of file diff --git a/app/lib/api/odooApi.ts b/app/lib/api/odooApi.ts new file mode 100644 index 0000000..c2c9d82 --- /dev/null +++ b/app/lib/api/odooApi.ts @@ -0,0 +1,56 @@ +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 }, + }; + console.log('ini adalah tipe',axiosParameter) + if (auth && typeof auth === 'object' && 'token' in 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(); + const response = await axios(axiosParameter); + return response.data; + } catch (error) { + console.log( JSON.stringify(error)); + } +} + + +export default odooApi
\ No newline at end of file |
