mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 18:52:06 +00:00
Feat: Update beer recs to be loaded on the client side
This commit is contained in:
@@ -6,6 +6,7 @@ import { FC, MutableRefObject, useContext, useRef } from 'react';
|
|||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import useBeerPostComments from '@/hooks/data-fetching/beer-comments/useBeerPostComments';
|
import useBeerPostComments from '@/hooks/data-fetching/beer-comments/useBeerPostComments';
|
||||||
import { useRouter } from 'next/router';
|
import { useRouter } from 'next/router';
|
||||||
|
import CreateCommentValidationSchema from '@/services/types/CommentSchema/CreateCommentValidationSchema';
|
||||||
import BeerCommentForm from './BeerCommentForm';
|
import BeerCommentForm from './BeerCommentForm';
|
||||||
|
|
||||||
import LoadingComponent from './LoadingComponent';
|
import LoadingComponent from './LoadingComponent';
|
||||||
@@ -20,29 +21,25 @@ const BeerPostCommentsSection: FC<BeerPostCommentsSectionProps> = ({ beerPost })
|
|||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
const pageNum = parseInt(router.query.comments_page as string, 10) || 1;
|
const pageNum = parseInt(router.query.comments_page as string, 10) || 1;
|
||||||
const PAGE_SIZE = 4;
|
const PAGE_SIZE = 15;
|
||||||
|
|
||||||
const { comments, isLoading, mutate, setSize, size, isLoadingMore, isAtEnd } =
|
const { comments, isLoading, mutate, setSize, size, isLoadingMore, isAtEnd } =
|
||||||
useBeerPostComments({
|
useBeerPostComments({ id: beerPost.id, pageNum, pageSize: PAGE_SIZE });
|
||||||
id: beerPost.id,
|
|
||||||
pageNum,
|
|
||||||
pageSize: PAGE_SIZE,
|
|
||||||
});
|
|
||||||
|
|
||||||
const commentSectionRef: MutableRefObject<HTMLDivElement | null> = useRef(null);
|
const commentSectionRef: MutableRefObject<HTMLDivElement | null> = useRef(null);
|
||||||
|
|
||||||
async function handleDeleteRequest(id: string) {
|
const handleDeleteRequest = async (id: string) => {
|
||||||
const response = await fetch(`/api/beer-comments/${id}`, { method: 'DELETE' });
|
const response = await fetch(`/api/beer-comments/${id}`, { method: 'DELETE' });
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error('Failed to delete comment.');
|
throw new Error('Failed to delete comment.');
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
async function handleEditRequest(
|
const handleEditRequest = async (
|
||||||
id: string,
|
id: string,
|
||||||
data: { content: string; rating: number },
|
data: z.infer<typeof CreateCommentValidationSchema>,
|
||||||
) {
|
) => {
|
||||||
const response = await fetch(`/api/beer-comments/${id}`, {
|
const response = await fetch(`/api/beer-comments/${id}`, {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
@@ -52,7 +49,7 @@ const BeerPostCommentsSection: FC<BeerPostCommentsSectionProps> = ({ beerPost })
|
|||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error('Failed to update comment.');
|
throw new Error('Failed to update comment.');
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="w-full space-y-3" ref={commentSectionRef}>
|
<div className="w-full space-y-3" ref={commentSectionRef}>
|
||||||
|
|||||||
@@ -1,40 +1,101 @@
|
|||||||
import BeerRecommendationQueryResult from '@/services/BeerPost/schema/BeerRecommendationQueryResult';
|
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { FunctionComponent } from 'react';
|
import { FC, MutableRefObject, useRef } from 'react';
|
||||||
|
import { useInView } from 'react-intersection-observer';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import useBeerRecommendations from '@/hooks/data-fetching/beer-posts/useBeerRecommendations';
|
||||||
|
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
|
||||||
|
import debounce from 'lodash/debounce';
|
||||||
|
import BeerRecommendationLoadingComponent from './BeerRecommendationLoadingComponent';
|
||||||
|
|
||||||
|
const BeerRecommendationsSection: FC<{
|
||||||
|
beerPost: z.infer<typeof beerPostQueryResult>;
|
||||||
|
}> = ({ beerPost }) => {
|
||||||
|
const PAGE_SIZE = 10;
|
||||||
|
|
||||||
|
const { beerPosts, isAtEnd, isLoadingMore, setSize, size } = useBeerRecommendations({
|
||||||
|
beerPost,
|
||||||
|
pageSize: PAGE_SIZE,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { ref: penultimateBeerPostRef } = useInView({
|
||||||
|
/**
|
||||||
|
* When the last beer post comes into view, call setSize from useBeerPostsByBrewery to
|
||||||
|
* load more beer posts.
|
||||||
|
*/
|
||||||
|
onChange: (visible) => {
|
||||||
|
if (!visible || isAtEnd) return;
|
||||||
|
debounce(() => setSize(size + 1), 200)();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const beerRecommendationsRef: MutableRefObject<HTMLDivElement | null> = useRef(null);
|
||||||
|
|
||||||
interface BeerRecommendationsProps {
|
|
||||||
beerRecommendations: BeerRecommendationQueryResult[];
|
|
||||||
}
|
|
||||||
const BeerRecommendations: FunctionComponent<BeerRecommendationsProps> = ({
|
|
||||||
beerRecommendations,
|
|
||||||
}) => {
|
|
||||||
return (
|
return (
|
||||||
<div className="card sticky top-2 h-full overflow-y-scroll">
|
<div className="card h-full" ref={beerRecommendationsRef}>
|
||||||
<div className="card-body space-y-3">
|
<div className="card-body">
|
||||||
{beerRecommendations.map((beerPost) => (
|
<>
|
||||||
<div key={beerPost.id} className="w-full">
|
<div className="my-2 flex flex-row items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
<Link className="link-hover" href={`/beers/${beerPost.id}`} scroll={false}>
|
<h3 className="text-3xl font-bold">Also check out</h3>
|
||||||
<h2 className="truncate text-lg font-bold lg:text-2xl">
|
</div>
|
||||||
{beerPost.name}
|
</div>
|
||||||
</h2>
|
|
||||||
|
{!!beerPosts.length && (
|
||||||
|
<div className="space-y-5">
|
||||||
|
{beerPosts.map((post, 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={post.id}
|
||||||
|
>
|
||||||
|
<div className="flex flex-col">
|
||||||
|
<Link className="link-hover link" href={`/beers/${post.id}`}>
|
||||||
|
<span className="text-xl font-semibold">{post.name}</span>
|
||||||
</Link>
|
</Link>
|
||||||
<Link href={`/breweries/${beerPost.brewery.id}`} className="link-hover">
|
|
||||||
<p className="text-md truncate font-semibold lg:text-xl">
|
<Link
|
||||||
{beerPost.brewery.name}
|
className="link-hover link"
|
||||||
</p>
|
href={`/breweries/${post.brewery.id}`}
|
||||||
|
>
|
||||||
|
<span className="text-lg font-semibold">{post.brewery.name}</span>
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-x-3 text-sm lg:text-lg">
|
<div>
|
||||||
<span>{beerPost.abv}% ABV</span>
|
<div>
|
||||||
<span>{beerPost.ibu} IBU</span>
|
<span className="text-lg font-medium">{post.type.name}</span>
|
||||||
|
</div>
|
||||||
|
<div className="space-x-2">
|
||||||
|
<span>{post.abv}% ABV</span>
|
||||||
|
<span>{post.ibu} IBU</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</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>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default BeerRecommendations;
|
export default BeerRecommendationsSection;
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
import UseBeerPostsByBrewery from '@/hooks/data-fetching/beer-posts/useBeerPostsByBrewery';
|
import UseBeerPostsByBrewery from '@/hooks/data-fetching/beer-posts/useBeerPostsByBrewery';
|
||||||
import BreweryPostQueryResult from '@/services/BreweryPost/types/BreweryPostQueryResult';
|
import BreweryPostQueryResult from '@/services/BreweryPost/types/BreweryPostQueryResult';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { FC } from 'react';
|
import { FC, MutableRefObject, useContext, useRef } from 'react';
|
||||||
import { useInView } from 'react-intersection-observer';
|
import { useInView } from 'react-intersection-observer';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import { FaPlus } from 'react-icons/fa';
|
import { FaPlus } from 'react-icons/fa';
|
||||||
|
import UserContext from '@/contexts/userContext';
|
||||||
import BeerRecommendationLoadingComponent from '../BeerById/BeerRecommendationLoadingComponent';
|
import BeerRecommendationLoadingComponent from '../BeerById/BeerRecommendationLoadingComponent';
|
||||||
|
|
||||||
interface BreweryCommentsSectionProps {
|
interface BreweryCommentsSectionProps {
|
||||||
@@ -13,6 +14,8 @@ interface BreweryCommentsSectionProps {
|
|||||||
|
|
||||||
const BreweryBeersSection: FC<BreweryCommentsSectionProps> = ({ breweryPost }) => {
|
const BreweryBeersSection: FC<BreweryCommentsSectionProps> = ({ breweryPost }) => {
|
||||||
const PAGE_SIZE = 2;
|
const PAGE_SIZE = 2;
|
||||||
|
const { user } = useContext(UserContext);
|
||||||
|
|
||||||
const { beerPosts, isAtEnd, isLoadingMore, setSize, size } = UseBeerPostsByBrewery({
|
const { beerPosts, isAtEnd, isLoadingMore, setSize, size } = UseBeerPostsByBrewery({
|
||||||
breweryId: breweryPost.id,
|
breweryId: breweryPost.id,
|
||||||
pageSize: PAGE_SIZE,
|
pageSize: PAGE_SIZE,
|
||||||
@@ -28,8 +31,10 @@ const BreweryBeersSection: FC<BreweryCommentsSectionProps> = ({ breweryPost }) =
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const beerRecommendationsRef: MutableRefObject<HTMLDivElement | null> = useRef(null);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="card">
|
<div className="card h-full" ref={beerRecommendationsRef}>
|
||||||
<div className="card-body">
|
<div className="card-body">
|
||||||
<>
|
<>
|
||||||
<div className="my-2 flex flex-row items-center justify-between">
|
<div className="my-2 flex flex-row items-center justify-between">
|
||||||
@@ -37,6 +42,7 @@ const BreweryBeersSection: FC<BreweryCommentsSectionProps> = ({ breweryPost }) =
|
|||||||
<h3 className="text-3xl font-bold">Brews</h3>
|
<h3 className="text-3xl font-bold">Brews</h3>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
|
{user && (
|
||||||
<Link
|
<Link
|
||||||
className={`btn-ghost btn-sm btn gap-2 rounded-2xl outline`}
|
className={`btn-ghost btn-sm btn gap-2 rounded-2xl outline`}
|
||||||
href={`/breweries/${breweryPost.id}/beers/create`}
|
href={`/breweries/${breweryPost.id}/beers/create`}
|
||||||
@@ -44,6 +50,7 @@ const BreweryBeersSection: FC<BreweryCommentsSectionProps> = ({ breweryPost }) =
|
|||||||
<FaPlus className="text-xl" />
|
<FaPlus className="text-xl" />
|
||||||
Add Beer
|
Add Beer
|
||||||
</Link>
|
</Link>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -49,9 +49,10 @@ const CommentsComponent: FC<CommentsComponentProps> = ({
|
|||||||
handleEditRequest,
|
handleEditRequest,
|
||||||
}) => {
|
}) => {
|
||||||
const { ref: penultimateCommentRef } = useInView({
|
const { ref: penultimateCommentRef } = useInView({
|
||||||
|
threshold: 0.1,
|
||||||
/**
|
/**
|
||||||
* When the second last comment comes into view, call setSize from useBeerPostComments
|
* When the last comment comes into view, call setSize from useBeerPostComments to
|
||||||
* to load more comments.
|
* load more comments.
|
||||||
*/
|
*/
|
||||||
onChange: (visible) => {
|
onChange: (visible) => {
|
||||||
if (!visible || isAtEnd) return;
|
if (!visible || isAtEnd) return;
|
||||||
@@ -62,9 +63,9 @@ const CommentsComponent: FC<CommentsComponentProps> = ({
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{!!comments.length && (
|
{!!comments.length && (
|
||||||
<div className="card bg-base-300 pb-6">
|
<div className="card h-full bg-base-300 pb-6">
|
||||||
{comments.map((comment, index) => {
|
{comments.map((comment, index) => {
|
||||||
const isPenultimateComment = index === comments.length - 2;
|
const isLastComment = index === comments.length - 1;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Attach a ref to the last comment in the list. When it comes into view, the
|
* Attach a ref to the last comment in the list. When it comes into view, the
|
||||||
@@ -72,7 +73,7 @@ const CommentsComponent: FC<CommentsComponentProps> = ({
|
|||||||
*/
|
*/
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
ref={isPenultimateComment ? penultimateCommentRef : undefined}
|
ref={isLastComment ? penultimateCommentRef : undefined}
|
||||||
key={comment.id}
|
key={comment.id}
|
||||||
>
|
>
|
||||||
<CommentCardBody
|
<CommentCardBody
|
||||||
|
|||||||
80
src/hooks/data-fetching/beer-posts/useBeerRecommendations.ts
Normal file
80
src/hooks/data-fetching/beer-posts/useBeerRecommendations.ts
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
|
||||||
|
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||||
|
import useSWRInfinite from 'swr/infinite';
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
interface UseBeerRecommendationsParams {
|
||||||
|
pageSize: number;
|
||||||
|
beerPost: z.infer<typeof beerPostQueryResult>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A custom hook using SWR to fetch beer recommendations from the API.
|
||||||
|
*
|
||||||
|
* @param options The options to use when fetching beer recommendations.
|
||||||
|
* @param options.pageSize The number of beer recommendations to fetch per page.
|
||||||
|
* @param options.beerPost The beer post to fetch recommendations for.
|
||||||
|
* @returns An object with the following properties:
|
||||||
|
*
|
||||||
|
* - `beerPosts`: The beer posts 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 UseBeerPostsByBrewery = ({ pageSize, beerPost }: UseBeerRecommendationsParams) => {
|
||||||
|
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(beerPostQueryResult).safeParse(parsed.data.payload);
|
||||||
|
if (!parsedPayload.success) {
|
||||||
|
throw new Error('API response validation failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
const pageCount = Math.ceil(parseInt(count as string, 10) / pageSize);
|
||||||
|
return {
|
||||||
|
beerPosts: parsedPayload.data,
|
||||||
|
pageCount,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const { data, error, isLoading, setSize, size } = useSWRInfinite(
|
||||||
|
(index) =>
|
||||||
|
`/api/beers/${beerPost.id}/recommendations/?page_num=${
|
||||||
|
index + 1
|
||||||
|
}&page_size=${pageSize}`,
|
||||||
|
fetcher,
|
||||||
|
);
|
||||||
|
|
||||||
|
const beerPosts = data?.flatMap((d) => d.beerPosts) ?? [];
|
||||||
|
const pageCount = data?.[0].pageCount ?? 0;
|
||||||
|
const isLoadingMore = size > 0 && data && typeof data[size - 1] === 'undefined';
|
||||||
|
const isAtEnd = !(size < data?.[0].pageCount!);
|
||||||
|
|
||||||
|
return {
|
||||||
|
beerPosts,
|
||||||
|
pageCount,
|
||||||
|
size,
|
||||||
|
setSize,
|
||||||
|
isLoading,
|
||||||
|
isLoadingMore,
|
||||||
|
isAtEnd,
|
||||||
|
error: error as unknown,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export default UseBeerPostsByBrewery;
|
||||||
63
src/pages/api/beers/[id]/recommendations.ts
Normal file
63
src/pages/api/beers/[id]/recommendations.ts
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
|
||||||
|
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
|
||||||
|
import ServerError from '@/config/util/ServerError';
|
||||||
|
import getBeerPostById from '@/services/BeerPost/getBeerPostById';
|
||||||
|
import getBeerRecommendations from '@/services/BeerPost/getBeerRecommendations';
|
||||||
|
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||||
|
import { NextApiRequest, NextApiResponse } from 'next';
|
||||||
|
import { createRouter } from 'next-connect';
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
interface BeerPostRequest extends NextApiRequest {
|
||||||
|
query: { id: string; page_num: string; page_size: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
const router = createRouter<
|
||||||
|
BeerPostRequest,
|
||||||
|
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
|
||||||
|
>();
|
||||||
|
|
||||||
|
const getBeerRecommendationsRequest = async (
|
||||||
|
req: BeerPostRequest,
|
||||||
|
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
|
||||||
|
) => {
|
||||||
|
const { id } = req.query;
|
||||||
|
|
||||||
|
const beerPost = await getBeerPostById(id);
|
||||||
|
|
||||||
|
if (!beerPost) {
|
||||||
|
throw new ServerError('Beer post not found', 404);
|
||||||
|
}
|
||||||
|
|
||||||
|
const pageNum = parseInt(req.query.page_num as string, 10);
|
||||||
|
const pageSize = parseInt(req.query.page_size as string, 10);
|
||||||
|
|
||||||
|
const { count, beerRecommendations } = await getBeerRecommendations({
|
||||||
|
beerPost,
|
||||||
|
pageNum,
|
||||||
|
pageSize,
|
||||||
|
});
|
||||||
|
|
||||||
|
res.setHeader('X-Total-Count', count);
|
||||||
|
res.status(200).json({
|
||||||
|
success: true,
|
||||||
|
message: 'Recommendations fetched successfully',
|
||||||
|
statusCode: 200,
|
||||||
|
payload: beerRecommendations,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
router.get(
|
||||||
|
validateRequest({
|
||||||
|
querySchema: z.object({
|
||||||
|
id: z.string().uuid(),
|
||||||
|
page_num: z.string().regex(/^[0-9]+$/),
|
||||||
|
page_size: z.string().regex(/^[0-9]+$/),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
getBeerRecommendationsRequest,
|
||||||
|
);
|
||||||
|
|
||||||
|
const handler = router.handler(NextConnectOptions);
|
||||||
|
|
||||||
|
export default handler;
|
||||||
@@ -7,10 +7,8 @@ import BeerPostCommentsSection from '@/components/BeerById/BeerPostCommentsSecti
|
|||||||
import BeerRecommendations from '@/components/BeerById/BeerRecommendations';
|
import BeerRecommendations from '@/components/BeerById/BeerRecommendations';
|
||||||
|
|
||||||
import getBeerPostById from '@/services/BeerPost/getBeerPostById';
|
import getBeerPostById from '@/services/BeerPost/getBeerPostById';
|
||||||
import getBeerRecommendations from '@/services/BeerPost/getBeerRecommendations';
|
|
||||||
|
|
||||||
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
|
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
|
||||||
import { BeerPost } from '@prisma/client';
|
|
||||||
|
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
@@ -21,13 +19,9 @@ import { Tab } from '@headlessui/react';
|
|||||||
|
|
||||||
interface BeerPageProps {
|
interface BeerPageProps {
|
||||||
beerPost: z.infer<typeof beerPostQueryResult>;
|
beerPost: z.infer<typeof beerPostQueryResult>;
|
||||||
beerRecommendations: (BeerPost & {
|
|
||||||
brewery: { id: string; name: string };
|
|
||||||
beerImages: { id: string; alt: string; url: string }[];
|
|
||||||
})[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const BeerByIdPage: NextPage<BeerPageProps> = ({ beerPost, beerRecommendations }) => {
|
const BeerByIdPage: NextPage<BeerPageProps> = ({ beerPost }) => {
|
||||||
const isDesktop = useMediaQuery('(min-width: 1024px)');
|
const isDesktop = useMediaQuery('(min-width: 1024px)');
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -72,7 +66,7 @@ const BeerByIdPage: NextPage<BeerPageProps> = ({ beerPost, beerRecommendations }
|
|||||||
<BeerPostCommentsSection beerPost={beerPost} />
|
<BeerPostCommentsSection beerPost={beerPost} />
|
||||||
</div>
|
</div>
|
||||||
<div className="w-[40%]">
|
<div className="w-[40%]">
|
||||||
<BeerRecommendations beerRecommendations={beerRecommendations} />
|
<BeerRecommendations beerPost={beerPost} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
@@ -90,7 +84,7 @@ const BeerByIdPage: NextPage<BeerPageProps> = ({ beerPost, beerRecommendations }
|
|||||||
<BeerPostCommentsSection beerPost={beerPost} />
|
<BeerPostCommentsSection beerPost={beerPost} />
|
||||||
</Tab.Panel>
|
</Tab.Panel>
|
||||||
<Tab.Panel>
|
<Tab.Panel>
|
||||||
<BeerRecommendations beerRecommendations={beerRecommendations} />
|
<BeerRecommendations beerPost={beerPost} />
|
||||||
</Tab.Panel>
|
</Tab.Panel>
|
||||||
</Tab.Panels>
|
</Tab.Panels>
|
||||||
</Tab.Group>
|
</Tab.Group>
|
||||||
@@ -109,12 +103,8 @@ export const getServerSideProps: GetServerSideProps<BeerPageProps> = async (cont
|
|||||||
return { notFound: true };
|
return { notFound: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
const { type, brewery, id } = beerPost;
|
|
||||||
const beerRecommendations = await getBeerRecommendations({ type, brewery, id });
|
|
||||||
|
|
||||||
const props = {
|
const props = {
|
||||||
beerPost: JSON.parse(JSON.stringify(beerPost)),
|
beerPost: JSON.parse(JSON.stringify(beerPost)),
|
||||||
beerRecommendations: JSON.parse(JSON.stringify(beerRecommendations)),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return { props };
|
return { props };
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import { FaArrowUp } from 'react-icons/fa';
|
|||||||
import LoadingCard from '@/components/ui/LoadingCard';
|
import LoadingCard from '@/components/ui/LoadingCard';
|
||||||
|
|
||||||
const BeerPage: NextPage = () => {
|
const BeerPage: NextPage = () => {
|
||||||
const PAGE_SIZE = 6;
|
const PAGE_SIZE = 20;
|
||||||
|
|
||||||
const { beerPosts, setSize, size, isLoading, isLoadingMore, isAtEnd } = useBeerPosts({
|
const { beerPosts, setSize, size, isLoading, isLoadingMore, isAtEnd } = useBeerPosts({
|
||||||
pageSize: PAGE_SIZE,
|
pageSize: PAGE_SIZE,
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ interface BreweryPageProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const BreweryPage: NextPage<BreweryPageProps> = () => {
|
const BreweryPage: NextPage<BreweryPageProps> = () => {
|
||||||
const PAGE_SIZE = 6;
|
const PAGE_SIZE = 20;
|
||||||
|
|
||||||
const { breweryPosts, setSize, size, isLoading, isLoadingMore, isAtEnd } =
|
const { breweryPosts, setSize, size, isLoading, isLoadingMore, isAtEnd } =
|
||||||
useBreweryPosts({
|
useBreweryPosts({
|
||||||
|
|||||||
@@ -1,22 +1,51 @@
|
|||||||
import DBClient from '@/prisma/DBClient';
|
import DBClient from '@/prisma/DBClient';
|
||||||
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
|
import BeerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
|
||||||
|
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
const getBeerRecommendations = async (
|
interface GetBeerRecommendationsArgs {
|
||||||
beerPost: Pick<z.infer<typeof beerPostQueryResult>, 'type' | 'brewery' | 'id'>,
|
beerPost: z.infer<typeof BeerPostQueryResult>;
|
||||||
) => {
|
pageNum: number;
|
||||||
const beerRecommendations = await DBClient.instance.beerPost.findMany({
|
pageSize: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const getBeerRecommendations = async ({
|
||||||
|
beerPost,
|
||||||
|
pageNum,
|
||||||
|
pageSize,
|
||||||
|
}: GetBeerRecommendationsArgs) => {
|
||||||
|
const skip = (pageNum - 1) * pageSize;
|
||||||
|
const take = pageSize;
|
||||||
|
const beerRecommendations: z.infer<typeof BeerPostQueryResult>[] =
|
||||||
|
await DBClient.instance.beerPost.findMany({
|
||||||
where: {
|
where: {
|
||||||
OR: [{ typeId: beerPost.type.id }, { breweryId: beerPost.brewery.id }],
|
OR: [{ typeId: beerPost.type.id }, { breweryId: beerPost.brewery.id }],
|
||||||
NOT: { id: beerPost.id },
|
NOT: { id: beerPost.id },
|
||||||
},
|
},
|
||||||
include: {
|
select: {
|
||||||
beerImages: { select: { id: true, path: true, caption: true, alt: true } },
|
id: true,
|
||||||
brewery: { select: { id: true, name: true } },
|
name: true,
|
||||||
|
ibu: true,
|
||||||
|
abv: true,
|
||||||
|
description: true,
|
||||||
|
createdAt: true,
|
||||||
|
type: { select: { name: true, id: true } },
|
||||||
|
brewery: { select: { name: true, id: true } },
|
||||||
|
postedBy: { select: { id: true, username: true } },
|
||||||
|
beerImages: { select: { path: true, caption: true, id: true, alt: true } },
|
||||||
|
},
|
||||||
|
take,
|
||||||
|
skip,
|
||||||
|
});
|
||||||
|
|
||||||
|
const count = await DBClient.instance.beerPost.count({
|
||||||
|
where: {
|
||||||
|
OR: [{ typeId: beerPost.type.id }, { breweryId: beerPost.brewery.id }],
|
||||||
|
NOT: { id: beerPost.id },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return beerRecommendations;
|
return { beerRecommendations, count };
|
||||||
};
|
};
|
||||||
|
|
||||||
export default getBeerRecommendations;
|
export default getBeerRecommendations;
|
||||||
|
|||||||
Reference in New Issue
Block a user