more files
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
let csrfToken: string | null = null
|
||||
|
||||
async function getCSRFToken(): Promise<string> {
|
||||
if (csrfToken) return csrfToken
|
||||
const res = await fetch('/api/v1/csrf', { credentials: 'include' })
|
||||
if (!res.ok) throw new Error('Failed to fetch CSRF token')
|
||||
csrfToken = res.headers.get('X-CSRF-Token') ?? ''
|
||||
return csrfToken
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
public readonly status: number,
|
||||
message: string,
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'ApiError'
|
||||
}
|
||||
}
|
||||
|
||||
interface RequestOptions extends RequestInit {
|
||||
json?: unknown
|
||||
}
|
||||
|
||||
async function request<T>(
|
||||
path: string,
|
||||
schema: z.ZodType<T>,
|
||||
options: RequestOptions = {},
|
||||
): Promise<T> {
|
||||
const { json, ...rest } = options
|
||||
const headers: Record<string, string> = {}
|
||||
|
||||
if (json !== undefined) {
|
||||
headers['Content-Type'] = 'application/json'
|
||||
}
|
||||
|
||||
const method = (rest.method ?? 'GET').toUpperCase()
|
||||
if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) {
|
||||
headers['X-CSRF-Token'] = await getCSRFToken()
|
||||
}
|
||||
|
||||
const res = await fetch(path, {
|
||||
...rest,
|
||||
credentials: 'include',
|
||||
headers: { ...headers, ...(rest.headers as Record<string, string> | undefined) },
|
||||
body: json !== undefined ? JSON.stringify(json) : rest.body,
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
let message = res.statusText
|
||||
try {
|
||||
const body = await res.json()
|
||||
if (typeof body.error === 'string') message = body.error
|
||||
} catch {}
|
||||
throw new ApiError(res.status, message)
|
||||
}
|
||||
|
||||
const data = await res.json()
|
||||
return schema.parse(data)
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: <T>(path: string, schema: z.ZodType<T>) => request(path, schema),
|
||||
post: <T>(path: string, schema: z.ZodType<T>, body: unknown) =>
|
||||
request(path, schema, { method: 'POST', json: body }),
|
||||
put: <T>(path: string, schema: z.ZodType<T>, body: unknown) =>
|
||||
request(path, schema, { method: 'PUT', json: body }),
|
||||
delete: <T>(path: string, schema: z.ZodType<T>) =>
|
||||
request(path, schema, { method: 'DELETE' }),
|
||||
}
|
||||
Reference in New Issue
Block a user