move CRUD operations to helpers

This commit is contained in:
Thomas Ruoff
2021-06-07 23:32:54 +02:00
parent 865bbb20fa
commit 92477e5325
9 changed files with 102 additions and 93 deletions

View File

@@ -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(',')
}
}

View File

@@ -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)