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 & { 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() }