mirror of
https://github.com/tomru/pfadi-bussle.git
synced 2026-03-03 06:27:11 +01:00
move CRUD operations to helpers
This commit is contained in:
40
helpers/fetch.ts
Normal file
40
helpers/fetch.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
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()
|
||||
}
|
||||
Reference in New Issue
Block a user