Files
pfadi-bussle/helpers/fetch.ts
2021-06-16 23:36:28 +02:00

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