import { defineEventHandler, getCookie, getRequestHeaders, getRequestURL, readBody } from 'h3' export default defineEventHandler(async (event) => { const { method } = event.node.req as any const headers = getRequestHeaders(event) const url = getRequestURL(event) const config = useRuntimeConfig() const apiOrigin = config.public.API_ORIGIN const apiVclaim = config.public.VCLAIM const apiVclaimSwagger = config.public.VCLAIM_SWAGGER const pathname = url.pathname.replace(/^\/api/, '') const isVclaim = pathname.includes('/vclaim') let targetUrl = apiOrigin + pathname + (url.search || '') if (pathname.includes('/vclaim')) { targetUrl = apiVclaim + pathname.replace('/vclaim', '') + (url.search || '') } if (pathname.includes('/vclaim-swagger')) { targetUrl = apiVclaimSwagger + pathname.replace('/vclaim-swagger', '') + (url.search || '') } const verificationId = headers['verification-id'] as string | undefined let bearer = '' if (verificationId) { bearer = getCookie(event, `Verification-${verificationId}`) || '' if (!bearer) bearer = getCookie(event, 'authentication') || '' } else { bearer = getCookie(event, 'authentication') || '' } const forwardHeaders = new Headers() if (!isVclaim) { if (headers['content-type']) forwardHeaders.set('Content-Type', headers['content-type']) forwardHeaders.set('Authorization', `Bearer ${bearer}`) } let body: any if (['POST', 'PATCH', 'PUT', 'DELETE'].includes(method)) { if (headers['content-type']?.includes('multipart/form-data')) { body = await readBody(event) } else { body = await readBody(event) forwardHeaders.set('Content-Type', 'application/json') body = JSON.stringify(body) } } const res = await fetch(targetUrl, { method, headers: forwardHeaders, body, }) if (isVclaim) { const resClone = res.clone() const responseBody = await resClone.json() return { status: resClone.status, headers: resClone.headers, ...responseBody, } } return res })