mirror of
https://github.com/tomru/pfadi-bussle.git
synced 2026-03-02 22:17:11 +01:00
41 lines
939 B
TypeScript
41 lines
939 B
TypeScript
import { ValidationError } from './validationError'
|
|
|
|
const DEFAULT_FETCH_OPTIONS = {
|
|
method: 'GET',
|
|
mode: 'cors' as RequestMode,
|
|
cache: 'no-cache' as RequestCache,
|
|
credentials: 'same-origin' as RequestCredentials,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
referrerPolicy: 'no-referrer' as ReferrerPolicy,
|
|
}
|
|
|
|
export type FetchOptions = Omit<RequestInit, 'body'> & {
|
|
body?: object
|
|
}
|
|
|
|
export default async function fetchJSON(
|
|
url: string,
|
|
options: FetchOptions = {}
|
|
) {
|
|
const response = await fetch(url, {
|
|
...DEFAULT_FETCH_OPTIONS,
|
|
...options,
|
|
body: !!options.body ? JSON.stringify(options.body) : undefined,
|
|
})
|
|
|
|
if (response.status === 400) {
|
|
const error = await response.json()
|
|
throw new ValidationError(error.errors)
|
|
}
|
|
|
|
if (!response.ok) {
|
|
throw Error(
|
|
'Sorry, konnte nicht gespeichert werden. Bitte versuch es später nochmal!'
|
|
)
|
|
}
|
|
|
|
return response.json()
|
|
}
|