Kansho/frontend/src/api.js

21 lines
688 B
JavaScript

export async function api(path, { token, method = 'GET', body } = {}) {
const headers = {}
if (token) headers['X-Auth-Token'] = token
if (body !== undefined) headers['Content-Type'] = 'application/json'
const response = await fetch(path, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined
})
const data = await response.json().catch(() => null)
if (!response.ok) {
const detail = data?.detail
const message = typeof detail === 'string' ? detail : (detail?.message || 'Anfrage fehlgeschlagen')
const error = new Error(message)
error.status = response.status
error.payload = data
throw error
}
return data
}