added better error messages for api-tests send

This commit is contained in:
Aaro Koivukangas
2024-09-22 23:23:21 +03:00
committed by Aaro Koivukangas
parent 0aa9844c4b
commit 9bcedea87f
+9 -5
View File
@@ -14,11 +14,15 @@ export const send = async <T extends Record<string, unknown>>(
headers.append('Content-Type', 'application/json')
if (token) headers.append('authorization', `bearer ${token}`)
const options = { body: method !== 'GET' ? JSON.stringify(body) : undefined, method, headers }
const response = await fetch(`${baseUrl}/${path}`, options)
if (response.status > 399) return { body: {} as T, status: response.status }
const responseText = await response.text()
if (!responseText) return { body: {} as T, status: response.status }
return { body: JSON.parse(responseText) as T, status: response.status }
try {
const response = await fetch(`${baseUrl}/${path}`, options)
if (response.status > 399) return { body: {} as T, status: response.status }
const responseText = await response.text()
if (!responseText) return { body: {} as T, status: response.status }
return { body: JSON.parse(responseText) as T, status: response.status }
} catch(e){
throw new Error(`Fetching ${baseUrl}/${path} failed: ${e}`)
}
}
export const setToken = (newToken: string) => (token = newToken)