Refactor: Organize api requests by type and remove toastContext

This commit is contained in:
Aaron William Po
2023-05-21 21:49:52 -04:00
parent 10bba6ab02
commit 27e72d3dcf
30 changed files with 345 additions and 180 deletions

View File

@@ -0,0 +1,42 @@
import CommentQueryResult from '@/services/types/CommentSchema/CommentQueryResult';
import CreateCommentValidationSchema from '@/services/types/CommentSchema/CreateCommentValidationSchema';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { z } from 'zod';
const BeerCommentValidationSchemaWithId = CreateCommentValidationSchema.extend({
beerPostId: z.string().uuid(),
});
const sendCreateBeerCommentRequest = async ({
beerPostId,
content,
rating,
}: z.infer<typeof BeerCommentValidationSchemaWithId>) => {
const response = await fetch(`/api/beers/${beerPostId}/comments`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ beerPostId, content, rating }),
});
if (!response.ok) {
throw new Error(response.statusText);
}
const data = await response.json();
const parsedResponse = APIResponseValidationSchema.safeParse(data);
if (!parsedResponse.success) {
throw new Error('Invalid API response');
}
const parsedPayload = CommentQueryResult.safeParse(parsedResponse.data.payload);
if (!parsedPayload.success) {
throw new Error('Invalid API response payload');
}
return parsedPayload.data;
};
export default sendCreateBeerCommentRequest;