45 lines
959 B
TypeScript
45 lines
959 B
TypeScript
import { userContext } from '@/context'
|
|
import type { User } from '@/lib/auth'
|
|
import type { LoaderFunctionArgs } from 'react-router'
|
|
|
|
export enum HttpMethod {
|
|
GET = 'GET',
|
|
POST = 'POST',
|
|
PUT = 'PUT',
|
|
PATCH = 'PATCH',
|
|
DELETE = 'DELETE'
|
|
}
|
|
|
|
type RequestArgs = {
|
|
url: string
|
|
method?: HttpMethod
|
|
headers?: HeadersInit
|
|
body?: BodyInit | null
|
|
request: LoaderFunctionArgs['request']
|
|
context: LoaderFunctionArgs['context']
|
|
}
|
|
|
|
export function request({
|
|
url,
|
|
method = HttpMethod.GET,
|
|
headers: _headers = {},
|
|
body = null,
|
|
request: { signal },
|
|
context
|
|
}: RequestArgs): Promise<Response> {
|
|
const user = context.get(userContext) as User
|
|
// @ts-ignore
|
|
const headers = new Headers(
|
|
Object.assign(_headers, { Authorization: `Bearer ${user.accessToken}` })
|
|
)
|
|
// @ts-ignore
|
|
const endpoint = new URL(url, context.cloudflare.env.API_URL)
|
|
|
|
return fetch(endpoint.toString(), {
|
|
method,
|
|
headers,
|
|
body,
|
|
signal
|
|
})
|
|
}
|