Fix: Update page count calc

This commit is contained in:
Aaron William Po
2023-10-30 12:21:51 -04:00
parent 67debcef81
commit 8093817ccc
2 changed files with 171 additions and 0 deletions

View File

@@ -0,0 +1,100 @@
import Link from 'next/link';
import { FC, MutableRefObject, useRef } from 'react';
import { useInView } from 'react-intersection-observer';
import { z } from 'zod';
import BeerStyleQueryResult from '@/services/BeerStyles/schema/BeerStyleQueryResult';
import useBeerPostsByBeerStyle from '@/hooks/data-fetching/beer-posts/useBeerPostsByBeerStyles';
import BeerRecommendationLoadingComponent from '../BeerById/BeerRecommendationLoadingComponent';
interface BeerStyleBeerSectionProps {
beerStyle: z.infer<typeof BeerStyleQueryResult>;
}
const BeerStyleBeerSection: FC<BeerStyleBeerSectionProps> = ({ beerStyle }) => {
const PAGE_SIZE = 2;
const { beerPosts, isAtEnd, isLoadingMore, setSize, size } = useBeerPostsByBeerStyle({
beerStyleId: beerStyle.id,
pageSize: PAGE_SIZE,
});
const { ref: penultimateBeerPostRef } = useInView({
/**
* When the last beer post comes into view, call setSize from useBeerPostsByBeerStyle
* to load more beer posts.
*/
onChange: (visible) => {
if (!visible || isAtEnd) return;
setSize(size + 1);
},
});
const beerRecommendationsRef: MutableRefObject<HTMLDivElement | null> = useRef(null);
return (
<div className="card h-full" ref={beerRecommendationsRef}>
<div className="card-body">
<>
<div className="my-2 flex flex-row items-center justify-between">
<div>
<h3 className="text-3xl font-bold">Brews</h3>
</div>
</div>
{!!beerPosts.length && (
<div className="space-y-5">
{beerPosts.map((beerPost, index) => {
const isPenultimateBeerPost = index === beerPosts.length - 2;
/**
* Attach a ref to the second last beer post in the list. When it comes
* into view, the component will call setSize to load more beer posts.
*/
return (
<div
ref={isPenultimateBeerPost ? penultimateBeerPostRef : undefined}
key={beerPost.id}
>
<div>
<Link className="link-hover link" href={`/beers/${beerPost.id}`}>
<span className="text-xl font-semibold">{beerPost.name}</span>
</Link>
</div>
<div>
<Link
className="link-hover link"
href={`/breweries/${beerPost.brewery.id}`}
>
<span className="text-xl font-semibold">
{beerPost.brewery.name}
</span>
</Link>
</div>
<div className="space-x-2">
<span>{beerPost.abv}% ABV</span>
<span>{beerPost.ibu} IBU</span>
</div>
</div>
);
})}
</div>
)}
{
/**
* If there are more beer posts to load, show a loading component with a
* skeleton loader and a loading spinner.
*/
!!isLoadingMore && !isAtEnd && (
<BeerRecommendationLoadingComponent length={PAGE_SIZE} />
)
}
</>
</div>
</div>
);
};
export default BeerStyleBeerSection;

View File

@@ -0,0 +1,71 @@
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
import DBClient from '@/prisma/DBClient';
import BeerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiRequest, NextApiResponse } from 'next';
import { createRouter } from 'next-connect';
import { z } from 'zod';
interface GetAllBeersByBeerStyleRequest extends NextApiRequest {
query: { page_size: string; page_num: string; id: string };
}
const getAllBeersByBeerStyle = async (
req: GetAllBeersByBeerStyleRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
// eslint-disable-next-line @typescript-eslint/naming-convention
const { page_size, page_num, id } = req.query;
const beers: z.infer<typeof BeerPostQueryResult>[] =
await DBClient.instance.beerPost.findMany({
where: { styleId: id },
take: parseInt(page_size, 10),
skip: parseInt(page_num, 10) * parseInt(page_size, 10),
select: {
id: true,
name: true,
ibu: true,
abv: true,
createdAt: true,
updatedAt: true,
description: true,
postedBy: { select: { username: true, id: true } },
brewery: { select: { name: true, id: true } },
style: { select: { name: true, id: true, description: true } },
beerImages: { select: { alt: true, path: true, caption: true, id: true } },
},
});
const pageCount = await DBClient.instance.beerPost.count({ where: { styleId: id } });
res.setHeader('X-Total-Count', pageCount);
res.status(200).json({
message: 'Beers fetched successfully',
statusCode: 200,
payload: beers,
success: true,
});
};
const router = createRouter<
GetAllBeersByBeerStyleRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>();
router.get(
validateRequest({
querySchema: z.object({
page_size: z.string().min(1),
page_num: z.string().min(1),
id: z.string().min(1),
}),
}),
getAllBeersByBeerStyle,
);
const handler = router.handler(NextConnectOptions);
export default handler;