mirror of
https://github.com/johndoe6345789/metabuilder.git
synced 2026-04-27 07:14:56 +00:00
code: request,nextjs,json (1 files)
This commit is contained in:
28
frontends/nextjs/src/lib/api/request-json.ts
Normal file
28
frontends/nextjs/src/lib/api/request-json.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
export type ApiError = {
|
||||
error?: string
|
||||
details?: string
|
||||
}
|
||||
|
||||
export async function requestJson<T>(url: string, init?: RequestInit): Promise<T> {
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(init?.headers ?? {}),
|
||||
},
|
||||
...init,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
let payload: ApiError | null = null
|
||||
try {
|
||||
payload = (await response.json()) as ApiError
|
||||
} catch {
|
||||
payload = null
|
||||
}
|
||||
|
||||
const message = payload?.error || `Request failed (${response.status})`
|
||||
throw new Error(message)
|
||||
}
|
||||
|
||||
return (await response.json()) as T
|
||||
}
|
||||
Reference in New Issue
Block a user