39 lines
1.0 KiB
TypeScript
39 lines
1.0 KiB
TypeScript
import type { Route } from './+types'
|
|
|
|
import type { User } from '@repo/auth/auth'
|
|
import { userContext } from '@repo/auth/context'
|
|
|
|
export const loader = proxy
|
|
export const action = proxy
|
|
|
|
async function proxy({
|
|
request,
|
|
context
|
|
}: Route.ActionArgs): Promise<Response> {
|
|
const pathname = new URL(request.url).pathname.replace(/^\/api\//, '')
|
|
const user = context.get(userContext) as User
|
|
const url = new URL(pathname, context.cloudflare.env.API_URL)
|
|
const headers = new Headers(request.headers)
|
|
|
|
headers.set('Authorization', `Bearer ${user.accessToken}`)
|
|
|
|
const r = await fetch(url.toString(), {
|
|
method: request.method,
|
|
headers,
|
|
...(['GET', 'HEAD'].includes(request.method)
|
|
? {}
|
|
: { body: await request.text() })
|
|
})
|
|
|
|
const contentType = r.headers.get('content-type') || ''
|
|
const body =
|
|
contentType.includes('application/json') || contentType.startsWith('text/')
|
|
? await r.text()
|
|
: await r.arrayBuffer()
|
|
|
|
return new Response(body, {
|
|
status: r.status,
|
|
headers: r.headers
|
|
})
|
|
}
|