feat: begin work on beer type page and associated api routes

This commit is contained in:
Aaron William Po
2023-09-17 20:27:33 -04:00
parent 7c42146751
commit 6b8682e686
12 changed files with 377 additions and 28 deletions

34
package-lock.json generated
View File

@@ -77,7 +77,7 @@
"onchange": "^7.1.0", "onchange": "^7.1.0",
"postcss": "^8.4.26", "postcss": "^8.4.26",
"prettier": "^3.0.0", "prettier": "^3.0.0",
"prettier-plugin-jsdoc": "^0.4.2", "prettier-plugin-jsdoc": "^1.0.2",
"prettier-plugin-tailwindcss": "^0.4.1", "prettier-plugin-tailwindcss": "^0.4.1",
"prisma": "^5.0.0", "prisma": "^5.0.0",
"tailwindcss": "^3.3.3", "tailwindcss": "^3.3.3",
@@ -3485,9 +3485,9 @@
"integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==" "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ=="
}, },
"node_modules/comment-parser": { "node_modules/comment-parser": {
"version": "1.3.1", "version": "1.4.0",
"resolved": "https://registry.npmjs.org/comment-parser/-/comment-parser-1.3.1.tgz", "resolved": "https://registry.npmjs.org/comment-parser/-/comment-parser-1.4.0.tgz",
"integrity": "sha512-B52sN2VNghyq5ofvUsqZjmk6YkihBX5vMSChmSK9v4ShjKf3Vk5Xcmgpw4o+iIgtrnM/u5FiMpz9VKb8lpBveA==", "integrity": "sha512-QLyTNiZ2KDOibvFPlZ6ZngVsZ/0gYnE6uTXi5aoDg8ed3AkJAz4sEje3Y8a29hQ1s6A99MZXe47fLAXQ1rTqaw==",
"dev": true, "dev": true,
"engines": { "engines": {
"node": ">= 12.0.0" "node": ">= 12.0.0"
@@ -8839,20 +8839,20 @@
} }
}, },
"node_modules/prettier-plugin-jsdoc": { "node_modules/prettier-plugin-jsdoc": {
"version": "0.4.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/prettier-plugin-jsdoc/-/prettier-plugin-jsdoc-0.4.2.tgz", "resolved": "https://registry.npmjs.org/prettier-plugin-jsdoc/-/prettier-plugin-jsdoc-1.0.2.tgz",
"integrity": "sha512-w2jnAQm3z0GAG0bhzVJeehzDtrhGMSxJjit5ApCc2oxWfc7+jmLAkbtdOXaSpfwZz3IWkk+PiQPeRrLNpbM+Mw==", "integrity": "sha512-mhLT3qiSmfzjOEDvgLntX3XmSJaiDrgoN7WmOp4IH2mZ6LhbvZAnPDJH3Rs0k1O6WR7HcmM92fU1ArB0ALLG+A==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"binary-searching": "^2.0.5", "binary-searching": "^2.0.5",
"comment-parser": "^1.3.1", "comment-parser": "^1.4.0",
"mdast-util-from-markdown": "^1.2.0" "mdast-util-from-markdown": "^1.2.0"
}, },
"engines": { "engines": {
"node": ">=12.0.0" "node": ">=14.13.1 || >=16.0.0"
}, },
"peerDependencies": { "peerDependencies": {
"prettier": ">=2.1.2" "prettier": "^3.0.0"
} }
}, },
"node_modules/prettier-plugin-tailwindcss": { "node_modules/prettier-plugin-tailwindcss": {
@@ -13925,9 +13925,9 @@
"integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==" "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ=="
}, },
"comment-parser": { "comment-parser": {
"version": "1.3.1", "version": "1.4.0",
"resolved": "https://registry.npmjs.org/comment-parser/-/comment-parser-1.3.1.tgz", "resolved": "https://registry.npmjs.org/comment-parser/-/comment-parser-1.4.0.tgz",
"integrity": "sha512-B52sN2VNghyq5ofvUsqZjmk6YkihBX5vMSChmSK9v4ShjKf3Vk5Xcmgpw4o+iIgtrnM/u5FiMpz9VKb8lpBveA==", "integrity": "sha512-QLyTNiZ2KDOibvFPlZ6ZngVsZ/0gYnE6uTXi5aoDg8ed3AkJAz4sEje3Y8a29hQ1s6A99MZXe47fLAXQ1rTqaw==",
"dev": true "dev": true
}, },
"concat-map": { "concat-map": {
@@ -17721,13 +17721,13 @@
"dev": true "dev": true
}, },
"prettier-plugin-jsdoc": { "prettier-plugin-jsdoc": {
"version": "0.4.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/prettier-plugin-jsdoc/-/prettier-plugin-jsdoc-0.4.2.tgz", "resolved": "https://registry.npmjs.org/prettier-plugin-jsdoc/-/prettier-plugin-jsdoc-1.0.2.tgz",
"integrity": "sha512-w2jnAQm3z0GAG0bhzVJeehzDtrhGMSxJjit5ApCc2oxWfc7+jmLAkbtdOXaSpfwZz3IWkk+PiQPeRrLNpbM+Mw==", "integrity": "sha512-mhLT3qiSmfzjOEDvgLntX3XmSJaiDrgoN7WmOp4IH2mZ6LhbvZAnPDJH3Rs0k1O6WR7HcmM92fU1ArB0ALLG+A==",
"dev": true, "dev": true,
"requires": { "requires": {
"binary-searching": "^2.0.5", "binary-searching": "^2.0.5",
"comment-parser": "^1.3.1", "comment-parser": "^1.4.0",
"mdast-util-from-markdown": "^1.2.0" "mdast-util-from-markdown": "^1.2.0"
} }
}, },

View File

@@ -81,7 +81,7 @@
"onchange": "^7.1.0", "onchange": "^7.1.0",
"postcss": "^8.4.26", "postcss": "^8.4.26",
"prettier": "^3.0.0", "prettier": "^3.0.0",
"prettier-plugin-jsdoc": "^0.4.2", "prettier-plugin-jsdoc": "^1.0.2",
"prettier-plugin-tailwindcss": "^0.4.1", "prettier-plugin-tailwindcss": "^0.4.1",
"prisma": "^5.0.0", "prisma": "^5.0.0",
"tailwindcss": "^3.3.3", "tailwindcss": "^3.3.3",

View File

@@ -1,5 +1,8 @@
class ServerError extends Error { class ServerError extends Error {
constructor(message: string, public statusCode: number) { constructor(
message: string,
public statusCode: number,
) {
super(message); super(message);
this.name = 'ServerError'; this.name = 'ServerError';
} }

View File

@@ -0,0 +1,74 @@
import BeerTypeQueryResult from '@/services/BeerTypes/schema/BeerTypeQueryResult';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import useSWRInfinite from 'swr/infinite';
import { z } from 'zod';
/**
* A custom hook using SWR to fetch beer types from the API.
*
* @param options The options to use when fetching beer types.
* @param options.pageSize The number of beer types to fetch per page.
* @returns An object with the following properties:
*
* - `beerTypes`: The beer types fetched from the API.
* - `error`: The error that occurred while fetching the data.
* - `isAtEnd`: A boolean indicating whether all data has been fetched.
* - `isLoading`: A boolean indicating whether the data is being fetched.
* - `isLoadingMore`: A boolean indicating whether more data is being fetched.
* - `pageCount`: The total number of pages of data.
* - `setSize`: A function to set the size of the data.
* - `size`: The size of the data.
*/
const useBeerTypes = ({ pageSize }: { pageSize: number }) => {
const fetcher = async (url: string) => {
const response = await fetch(url);
if (!response.ok) {
throw new Error(response.statusText);
}
const json = await response.json();
const count = response.headers.get('X-Total-Count');
const parsed = APIResponseValidationSchema.safeParse(json);
if (!parsed.success) {
throw new Error('API response validation failed');
}
const parsedPayload = z.array(BeerTypeQueryResult).safeParse(parsed.data.payload);
if (!parsedPayload.success) {
console.log(parsedPayload.error);
throw new Error('API response validation failed');
}
const pageCount = Math.ceil(parseInt(count as string, 10) / pageSize);
return {
beerTypes: parsedPayload.data,
pageCount,
};
};
const { data, error, isLoading, setSize, size } = useSWRInfinite(
(index) => `/api/beers/types?page_num=${index + 1}&page_size=${pageSize}`,
fetcher,
{ parallel: true },
);
const beerTypes = data?.flatMap((d) => d.beerTypes) ?? [];
const pageCount = data?.[0].pageCount ?? 0;
const isLoadingMore = size > 0 && data && typeof data[size - 1] === 'undefined';
const isAtEnd = !(size < data?.[0].pageCount!);
return {
beerTypes,
error: error as unknown,
isAtEnd,
isLoading,
isLoadingMore,
pageCount,
setSize,
size,
};
};
export default useBeerTypes;

View File

@@ -53,7 +53,7 @@ const editComment = async (
id, id,
}); });
res.status(200).json({ res.status(200).json({
success: true, success: true,
message: 'Comment updated successfully', message: 'Comment updated successfully',
statusCode: 200, statusCode: 200,

View File

@@ -0,0 +1,82 @@
import { UserExtendedNextApiRequest } from '@/config/auth/types';
import getCurrentUser from '@/config/nextConnect/middleware/getCurrentUser';
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
import DBClient from '@/prisma/DBClient';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiRequest, NextApiResponse } from 'next';
import { createRouter } from 'next-connect';
import { z } from 'zod';
const BeerTypeValidationSchema = z.object({
id: z.string().cuid(),
name: z.string(),
postedBy: z.object({
id: z.string().cuid(),
username: z.string(),
}),
createdAt: z.date(),
updatedAt: z.date().nullable(),
});
const CreateBeerTypeValidationSchema = BeerTypeValidationSchema.omit({
id: true,
postedBy: true,
createdAt: true,
updatedAt: true,
});
interface CreateBeerTypeRequest extends UserExtendedNextApiRequest {
body: z.infer<typeof CreateBeerTypeValidationSchema>;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface GetBeerTypeRequest extends NextApiRequest {
query: {
id: string;
};
}
const createBeerType = async (
req: CreateBeerTypeRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const user = req.user!;
const { name } = req.body;
const newBeerType = await DBClient.instance.beerType.create({
data: {
name,
postedBy: { connect: { id: user.id } },
},
select: {
id: true,
name: true,
postedBy: { select: { id: true, username: true } },
createdAt: true,
updatedAt: true,
},
});
res.status(200).json({
message: 'Beer posts retrieved successfully',
statusCode: 200,
payload: newBeerType,
success: true,
});
};
const router = createRouter<
CreateBeerTypeRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>();
router.get(
validateRequest({ bodySchema: CreateBeerTypeValidationSchema }),
getCurrentUser,
createBeerType,
);
const handler = router.handler();
export default handler;

View File

@@ -0,0 +1,51 @@
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
import DBClient from '@/prisma/DBClient';
import getAllBeerTypes from '@/services/BeerTypes/getAllBeerTypes';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiRequest, NextApiResponse } from 'next';
import { createRouter } from 'next-connect';
import { z } from 'zod';
interface GetBeerTypesRequest extends NextApiRequest {
query: { page_num: string; page_size: string };
}
const getBeerTypes = async (
req: GetBeerTypesRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const pageNum = parseInt(req.query.page_num, 10);
const pageSize = parseInt(req.query.page_size, 10);
const beerTypes = await getAllBeerTypes(pageNum, pageSize);
const beerTypeCount = await DBClient.instance.beerType.count();
res.setHeader('X-Total-Count', beerTypeCount);
res.status(200).json({
message: 'Beer types retrieved successfully',
statusCode: 200,
payload: beerTypes,
success: true,
});
};
const router = createRouter<
GetBeerTypesRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>();
router.get(
validateRequest({
querySchema: z.object({
page_num: z.string().regex(/^\d+$/),
page_size: z.string().regex(/^\d+$/),
}),
}),
getBeerTypes,
);
const handler = router.handler();
export default handler;

View File

@@ -0,0 +1,104 @@
import LoadingCard from '@/components/ui/LoadingCard';
import Spinner from '@/components/ui/Spinner';
import useBeerTypes from '@/hooks/data-fetching/beer-types/useBeerTypes';
import { NextPage } from 'next';
import Head from 'next/head';
import { MutableRefObject, useRef } from 'react';
import { FaArrowUp } from 'react-icons/fa';
import { useInView } from 'react-intersection-observer';
const BeerTypePage: NextPage = () => {
const PAGE_SIZE = 20;
const pageRef: MutableRefObject<HTMLDivElement | null> = useRef(null);
const { beerTypes, isLoading, isLoadingMore, isAtEnd, size, setSize, error } =
useBeerTypes({
pageSize: PAGE_SIZE,
});
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { ref: lastBeerTypeRef } = useInView({
onChange: (visible) => {
if (!visible || isAtEnd) return;
setSize(size + 1);
},
});
console.log(error);
console.log(beerTypes);
return (
<>
<Head>
<title>Beer Types | The Biergarten App</title>
<meta
name="description"
content="Find beers made by breweries near you and around the world."
/>
</Head>
<div className="flex items-center justify-center bg-base-100" ref={pageRef}>
<div className="my-10 flex w-10/12 flex-col space-y-4 lg:w-8/12 2xl:w-7/12">
<header className="my-10 flex justify-between lg:flex-row">
<div>
<h1 className="text-4xl font-bold lg:text-6xl">The Biergarten App</h1>
<h2 className="text-2xl font-bold lg:text-4xl">Beers</h2>
</div>
</header>
<div className="grid gap-6 xl:grid-cols-2">
{!!beerTypes.length && !isLoading && (
<>
{beerTypes.map((beerType, i) => {
return (
<div
key={beerType.id}
ref={beerTypes.length === i + 1 ? lastBeerTypeRef : undefined}
>
{beerType.name}
</div>
);
})}
</>
)}
{(isLoading || isLoadingMore) && (
<>
{Array.from({ length: PAGE_SIZE }, (_, i) => (
<LoadingCard key={i} />
))}
</>
)}
</div>
{(isLoading || isLoadingMore) && (
<div className="flex h-32 w-full items-center justify-center">
<Spinner size="sm" />
</div>
)}
{isAtEnd && !isLoading && (
<div className="flex h-20 items-center justify-center text-center">
<div
className="tooltip tooltip-bottom"
data-tip="Scroll back to top of page."
>
<button
type="button"
className="btn-ghost btn-sm btn"
aria-label="Scroll back to top of page."
onClick={() => {
pageRef.current?.scrollIntoView({
behavior: 'smooth',
});
}}
>
<FaArrowUp />
</button>
</div>
</div>
)}
</div>
</div>
</>
);
};
export default BeerTypePage;

View File

@@ -0,0 +1,24 @@
import DBClient from '@/prisma/DBClient';
import { z } from 'zod';
import BeerTypeQueryResult from './schema/BeerTypeQueryResult';
const getAllBeerTypes = async (
pageNum: number,
pageSize: number,
): Promise<z.infer<typeof BeerTypeQueryResult>[]> => {
const types = await DBClient.instance.beerType.findMany({
take: pageSize,
skip: (pageNum - 1) * pageSize,
select: {
id: true,
name: true,
postedBy: { select: { id: true, username: true } },
createdAt: true,
updatedAt: true,
},
});
return types;
};
export default getAllBeerTypes;

View File

@@ -0,0 +1,14 @@
import { z } from 'zod';
const BeerTypeQueryResult = z.object({
id: z.string().cuid(),
name: z.string(),
postedBy: z.object({
id: z.string().cuid(),
username: z.string(),
}),
createdAt: z.coerce.date(),
updatedAt: z.coerce.date().nullable(),
});
export default BeerTypeQueryResult;

View File

@@ -1,10 +1,6 @@
import toast from 'react-hot-toast'; import toast from 'react-hot-toast';
/** /** @param error - The error to display. Creates a toast message with the error message. */
* @param error - The error to display.
*
* Creates a toast message with the error message.
*/
const createErrorToast = (error: unknown) => { const createErrorToast = (error: unknown) => {
const errorMessage = error instanceof Error ? error.message : 'Something went wrong.'; const errorMessage = error instanceof Error ? error.message : 'Something went wrong.';
toast.error(errorMessage); toast.error(errorMessage);

View File

@@ -36,9 +36,10 @@ export type ExtendedGetServerSideProps<
* @returns A promise that resolves to a `GetServerSidePropsResult` object with props for * @returns A promise that resolves to a `GetServerSidePropsResult` object with props for
* the wrapped component. * the wrapped component.
* *
* If authentication is successful, the `GetServerSidePropsResult` will include props * - If authentication is successful, the `GetServerSidePropsResult` will include props
* generated by the wrapped component's `getServerSideProps` method. If authentication * generated by the wrapped component's `getServerSideProps` method.
* fails, the `GetServerSidePropsResult` will include a redirect to the login page. * - If authentication fails, the `GetServerSidePropsResult` will include a redirect to the
* login page.
*/ */
const withPageAuthRequired = const withPageAuthRequired =