mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 18:52:06 +00:00
Refactor api requests and components out of pages
This commit is contained in:
40
requests/sendCreateBeerPostRequest.ts
Normal file
40
requests/sendCreateBeerPostRequest.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import BeerPostValidationSchema from '@/validation/BeerPostValidationSchema';
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
import { z } from 'zod';
|
||||
|
||||
const sendCreateBeerPostRequest = async (
|
||||
data: z.infer<typeof BeerPostValidationSchema>,
|
||||
) => {
|
||||
const response = await fetch('/api/beers/create', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
const json = await response.json();
|
||||
|
||||
const parsed = APIResponseValidationSchema.safeParse(json);
|
||||
|
||||
if (!parsed.success) {
|
||||
throw new Error('Invalid API response');
|
||||
}
|
||||
|
||||
const { payload } = parsed.data;
|
||||
|
||||
if (
|
||||
!(
|
||||
payload &&
|
||||
typeof payload === 'object' &&
|
||||
'id' in payload &&
|
||||
typeof payload.id === 'string'
|
||||
)
|
||||
) {
|
||||
throw new Error('Invalid API response');
|
||||
}
|
||||
|
||||
return payload;
|
||||
};
|
||||
|
||||
export default sendCreateBeerPostRequest;
|
||||
Reference in New Issue
Block a user