import { string } from 'alga-js' const getToken = async () => { const config = useRuntimeConfig() return await $fetch(config.api.dhlurl+'/account/auth/ropc/v1/token', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' }, body: `grant_type=password&username=${string.urlEncode(config.api.dhluser)}&password=${string.urlEncode(config.api.dhlpass)}&client_id=${string.urlEncode(config.api.dhlkey)}&client_secret=${string.urlEncode(config.api.dhlsecret)}` }) } export default async function dhlHelper(event: any, url: string, method: string = 'GET', body: any) { const config = useRuntimeConfig() let token = getCookie(event, 'logship_bdhtl') ?? '' let options: any = {} if(body) { options = { ...options, body: body } } if(token === '') { const res = await getToken() if(res?.access_token) { token = res.access_token setCookie(event, 'logship_bdhtl', token) } } try { return await $fetch(config.api.dhlurl+'/'+url, { method: method, headers: { Accept: 'application/json', 'Content-Type': 'application/json', Authorization: 'Bearer ' + token }, ...options }) } catch(err: any) { const res2 = await getToken() if(res2?.access_token) { token = res2.access_token setCookie(event, 'logship_bdhtl', token) } return await $fetch(config.api.dhlurl+'/'+url, { method: method, headers: { Accept: 'application/json', 'Content-Type': 'application/json', Authorization: 'Bearer ' + token }, ...options }) } }