mirror of
https://github.com/tomru/pfadi-bussle.git
synced 2026-03-03 22:47:15 +01:00
move CRUD operations to helpers
This commit is contained in:
@@ -1,39 +0,0 @@
|
||||
import { VALIDATION_ERRORS } from '../../../db/enums'
|
||||
|
||||
interface ValidationErrors {
|
||||
[key: string]: { properties: { message: string }; kind: string }
|
||||
}
|
||||
|
||||
function getDefinedValidationMessage(kind: string) {
|
||||
switch (kind) {
|
||||
case VALIDATION_ERRORS.AT_LEAST_ONE_DAY_BOOKED:
|
||||
return 'Mindestens ein angefragter Tag ist nicht mehr verfügbar'
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export class ValidationError extends Error {
|
||||
private errors: ValidationErrors
|
||||
|
||||
constructor(errors: ValidationErrors) {
|
||||
super()
|
||||
|
||||
if (Error.captureStackTrace) {
|
||||
Error.captureStackTrace(this, ValidationError)
|
||||
}
|
||||
this.name = this.constructor.name
|
||||
this.errors = errors
|
||||
}
|
||||
|
||||
get message() {
|
||||
return Object.entries<{ properties: { message: string }; kind: string }>(
|
||||
this.errors
|
||||
)
|
||||
.map(([_key, value]) => {
|
||||
const validationMessage = getDefinedValidationMessage(value.kind)
|
||||
return validationMessage || `${value?.properties?.message}`
|
||||
})
|
||||
.join(',')
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import React, { useEffect, useReducer } from 'react'
|
||||
import { useRouter } from 'next/router'
|
||||
import { clearBookingData, loadBookingData } from '../../../helpers/storage'
|
||||
import { ValidationError } from './validationError'
|
||||
|
||||
import { createBooking } from '../../../helpers/booking'
|
||||
|
||||
interface WizardFormData {
|
||||
startDate: string
|
||||
@@ -136,33 +137,6 @@ const initialState: WizardStoreState = {
|
||||
dataStoredLoaded: undefined,
|
||||
}
|
||||
|
||||
async function createBooking(formData: WizardFormData) {
|
||||
const response = await fetch('/api/booking', {
|
||||
method: 'POST',
|
||||
mode: 'cors',
|
||||
cache: 'no-cache',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
referrerPolicy: 'no-referrer',
|
||||
body: JSON.stringify(formData),
|
||||
})
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
export default function WizardStore({ children }) {
|
||||
const router = useRouter()
|
||||
const [state, dispatch] = useReducer(reducer, initialState)
|
||||
|
||||
Reference in New Issue
Block a user