This commit is contained in:
1 parent
5b2fbb46ef
commit
0d310c2732
5 files changed
+289
-2
No files matched your search
@@ -5,15 +5,18 @@ interface ApiEnvelope<T> {
|
||||
}
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
// FormData needs the browser to set multipart Content-Type with its boundary
|
||||
const isForm = init?.body instanceof FormData
|
||||
const res = await fetch(path, {
|
||||
...init,
|
||||
credentials: 'same-origin',
|
||||
headers: { 'Content-Type': 'application/json', ...(init?.headers ?? {}) },
|
||||
headers: { ...(isForm ? {} : { 'Content-Type': 'application/json' }), ...(init?.headers ?? {}) },
|
||||
})
|
||||
|
||||
if (res.status === 204) return undefined as T
|
||||
|
||||
const body = (await res.json()) as ApiEnvelope<T>
|
||||
// A proxy (e.g. nginx 413) may answer with a non-JSON body
|
||||
const body = (await res.json().catch(() => ({}))) as Partial<ApiEnvelope<T>>
|
||||
|
||||
if (!res.ok) {
|
||||
const message = Array.isArray(body.message) ? body.message.join(', ') : body.message
|
||||
@@ -36,5 +39,6 @@ export const apiClient = {
|
||||
get: <T>(path: string) => request<T>(path),
|
||||
post: <T>(path: string, body?: unknown) => request<T>(path, { method: 'POST', body: JSON.stringify(body) }),
|
||||
patch: <T>(path: string, body?: unknown) => request<T>(path, { method: 'PATCH', body: JSON.stringify(body) }),
|
||||
upload: <T>(path: string, form: FormData) => request<T>(path, { method: 'POST', body: form }),
|
||||
delete: (path: string) => request<void>(path, { method: 'DELETE' }),
|
||||
}
|
||||
Reference in new issue
Block a user