mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 10:42:08 +00:00
Refactor: Organize api requests by type and remove toastContext
This commit is contained in:
36
src/requests/BeerPost/sendCreateBeerPostRequest.ts
Normal file
36
src/requests/BeerPost/sendCreateBeerPostRequest.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
|
||||
import CreateBeerPostValidationSchema from '@/services/BeerPost/schema/CreateBeerPostValidationSchema';
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
import { z } from 'zod';
|
||||
|
||||
const sendCreateBeerPostRequest = async (
|
||||
data: z.infer<typeof CreateBeerPostValidationSchema>,
|
||||
) => {
|
||||
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, success, message } = parsed.data;
|
||||
|
||||
if (!success) {
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
const parsedPayload = beerPostQueryResult.safeParse(payload);
|
||||
|
||||
if (!parsedPayload.success) {
|
||||
throw new Error('Invalid API response payload');
|
||||
}
|
||||
|
||||
return parsedPayload.data;
|
||||
};
|
||||
|
||||
export default sendCreateBeerPostRequest;
|
||||
Reference in New Issue
Block a user