graphicek/client/src/api/request.ts

46 lines
797 B
TypeScript
Raw Normal View History

2022-08-21 22:27:31 +02:00
export class RequestError extends Error {
constructor(public response: Response, message: string) {
super(message)
}
}
export class ResponseEmptyError extends RequestError {
constructor(response: Response, message: string) {
super(response, message)
}
}
export const request = async <T = void>(
url: string,
options?: RequestInit,
type: 'json' | 'void' = 'json'
) => {
const response = await fetch(url, options)
if (!response.ok) {
throw new RequestError(
response,
`${response.status} ${response.statusText}`
)
}
if (type === 'void') {
return
}
const text = await response.text()
if (!text) {
if (type === 'json') {
throw new ResponseEmptyError(
response,
'Expected json, got empty response'
)
}
return
}
return JSON.parse(text) as T
}