chore: scaffold turbo monorepo with hono api and react admin web
This commit is contained in:
55
apps/web/src/lib/api-client.ts
Normal file
55
apps/web/src/lib/api-client.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { PROBLEM_CONTENT_TYPE, type ProblemDetails } from '@superlist/shared'
|
||||
|
||||
const baseUrl = import.meta.env.VITE_API_URL ?? 'http://localhost:3000'
|
||||
|
||||
/** Error thrown when the API answers with a RFC 9457 Problem Details payload. */
|
||||
export class ApiError extends Error {
|
||||
readonly problem: ProblemDetails
|
||||
|
||||
constructor(problem: ProblemDetails) {
|
||||
super(problem.title)
|
||||
this.name = 'ApiError'
|
||||
this.problem = problem
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads a Problem Details body, falling back to a generic problem. */
|
||||
export async function readProblem(response: Response): Promise<ProblemDetails> {
|
||||
const contentType = response.headers.get('content-type') ?? ''
|
||||
|
||||
if (contentType.includes(PROBLEM_CONTENT_TYPE)) {
|
||||
try {
|
||||
return (await response.json()) as ProblemDetails
|
||||
} catch {
|
||||
// fall through to the generic problem below
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'about:blank',
|
||||
title: response.statusText || 'Request failed',
|
||||
status: response.status,
|
||||
}
|
||||
}
|
||||
|
||||
/** Thin `fetch` wrapper: JSON by default, sessions enabled, problems as errors. */
|
||||
export async function apiFetch<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
const response = await fetch(`${baseUrl}${path}`, {
|
||||
credentials: 'include',
|
||||
...init,
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
...init.headers,
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new ApiError(await readProblem(response))
|
||||
}
|
||||
|
||||
if (response.status === 204) {
|
||||
return undefined as T
|
||||
}
|
||||
|
||||
return (await response.json()) as T
|
||||
}
|
||||
Reference in New Issue
Block a user