mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 10:42:08 +00:00
Refactor api requests and components out of pages
This commit is contained in:
@@ -2,5 +2,6 @@
|
|||||||
"semi": true,
|
"semi": true,
|
||||||
"trailingComma": "all",
|
"trailingComma": "all",
|
||||||
"singleQuote": true,
|
"singleQuote": true,
|
||||||
"printWidth": 90
|
"printWidth": 90,
|
||||||
|
"plugins": ["prettier-plugin-jsdoc"]
|
||||||
}
|
}
|
||||||
|
|||||||
78
components/BeerById/BeerInfoHeader.tsx
Normal file
78
components/BeerById/BeerInfoHeader.tsx
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
import BeerPostQueryResult from '@/services/BeerPost/types/BeerPostQueryResult';
|
||||||
|
import Link from 'next/link';
|
||||||
|
import formatDistanceStrict from 'date-fns/formatDistanceStrict';
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { FaRegThumbsUp, FaThumbsUp } from 'react-icons/fa';
|
||||||
|
|
||||||
|
const BeerInfoHeader: React.FC<{ beerPost: BeerPostQueryResult }> = ({ beerPost }) => {
|
||||||
|
const createdAtDate = new Date(beerPost.createdAt);
|
||||||
|
const timeDistance = formatDistanceStrict(createdAtDate, Date.now());
|
||||||
|
|
||||||
|
const [isLiked, setIsLiked] = useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex h-full flex-col justify-center bg-base-300 p-10">
|
||||||
|
<h1 className="text-4xl font-bold">{beerPost.name}</h1>
|
||||||
|
<h2 className="text-2xl font-semibold">
|
||||||
|
by{' '}
|
||||||
|
<Link
|
||||||
|
href={`/breweries/${beerPost.brewery.id}`}
|
||||||
|
className="link-hover link text-2xl font-semibold"
|
||||||
|
>
|
||||||
|
{beerPost.brewery.name}
|
||||||
|
</Link>
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
<h3 className="italic">
|
||||||
|
posted by{' '}
|
||||||
|
<Link href={`/users/${beerPost.postedBy.id}`} className="link-hover link">
|
||||||
|
{beerPost.postedBy.username}
|
||||||
|
</Link>
|
||||||
|
{` ${timeDistance}`} ago
|
||||||
|
</h3>
|
||||||
|
|
||||||
|
<p>{beerPost.description}</p>
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<div>
|
||||||
|
<div className="mb-1">
|
||||||
|
<Link
|
||||||
|
className="text-lg font-medium"
|
||||||
|
href={`/beers/types/${beerPost.type.id}`}
|
||||||
|
>
|
||||||
|
{beerPost.type.name}
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="mr-4 text-lg font-medium">{beerPost.abv}% ABV</span>
|
||||||
|
<span className="text-lg font-medium">{beerPost.ibu} IBU</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="card-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`btn gap-2 rounded-2xl ${
|
||||||
|
!isLiked ? 'btn-ghost outline' : 'btn-primary'
|
||||||
|
}`}
|
||||||
|
onClick={() => {
|
||||||
|
setIsLiked(!isLiked);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{isLiked ? (
|
||||||
|
<>
|
||||||
|
<FaThumbsUp className="text-2xl" />
|
||||||
|
<span>Liked</span>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<FaRegThumbsUp className="text-2xl" />
|
||||||
|
<span>Like</span>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default BeerInfoHeader;
|
||||||
21
components/BeerById/CommentCard.tsx
Normal file
21
components/BeerById/CommentCard.tsx
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import BeerPostQueryResult from '@/services/BeerPost/types/BeerPostQueryResult';
|
||||||
|
import formatDistanceStrict from 'date-fns/formatDistanceStrict';
|
||||||
|
|
||||||
|
const CommentCard: React.FC<{
|
||||||
|
comment: BeerPostQueryResult['beerComments'][number];
|
||||||
|
}> = ({ comment }) => {
|
||||||
|
return (
|
||||||
|
<div className="card bg-base-300">
|
||||||
|
<div className="card-body">
|
||||||
|
<h3 className="text-2xl font-semibold">{comment.postedBy.username}</h3>
|
||||||
|
<h4 className="italic">{`posted ${formatDistanceStrict(
|
||||||
|
new Date(comment.createdAt),
|
||||||
|
new Date(),
|
||||||
|
)} ago`}</h4>
|
||||||
|
<p>{comment.content}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default CommentCard;
|
||||||
@@ -1,12 +1,14 @@
|
|||||||
import { NewBeerInfo } from '@/pages/api/beers/create';
|
|
||||||
import BreweryPostQueryResult from '@/services/BreweryPost/types/BreweryPostQueryResult';
|
import BreweryPostQueryResult from '@/services/BreweryPost/types/BreweryPostQueryResult';
|
||||||
import { BeerType } from '@prisma/client';
|
import { BeerType } from '@prisma/client';
|
||||||
|
|
||||||
import { FunctionComponent } from 'react';
|
import { FunctionComponent } from 'react';
|
||||||
import { SubmitHandler, useForm } from 'react-hook-form';
|
import { SubmitHandler, useForm } from 'react-hook-form';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import Button from './ui/Button';
|
import BeerPostValidationSchema from '@/validation/BeerPostValidationSchema';
|
||||||
|
import Router from 'next/router';
|
||||||
|
import sendCreateBeerPostRequest from '@/requests/sendCreateBeerPostRequest';
|
||||||
|
import Button from './ui/forms/Button';
|
||||||
import FormError from './ui/forms/FormError';
|
import FormError from './ui/forms/FormError';
|
||||||
import FormInfo from './ui/forms/FormInfo';
|
import FormInfo from './ui/forms/FormInfo';
|
||||||
import FormLabel from './ui/forms/FormLabel';
|
import FormLabel from './ui/forms/FormLabel';
|
||||||
@@ -15,34 +17,18 @@ import FormSelect from './ui/forms/FormSelect';
|
|||||||
import FormTextArea from './ui/forms/FormTextArea';
|
import FormTextArea from './ui/forms/FormTextArea';
|
||||||
import FormTextInput from './ui/forms/FormTextInput';
|
import FormTextInput from './ui/forms/FormTextInput';
|
||||||
|
|
||||||
type IFormInput = z.infer<typeof NewBeerInfo>;
|
type BeerPostT = z.infer<typeof BeerPostValidationSchema>;
|
||||||
|
|
||||||
interface BeerFormProps {
|
interface BeerFormProps {
|
||||||
type: 'edit' | 'create';
|
formType: 'edit' | 'create';
|
||||||
// eslint-disable-next-line react/require-default-props
|
// eslint-disable-next-line react/require-default-props
|
||||||
defaultValues?: IFormInput;
|
defaultValues?: BeerPostT;
|
||||||
breweries?: BreweryPostQueryResult[];
|
breweries?: BreweryPostQueryResult[];
|
||||||
types?: BeerType[];
|
types?: BeerType[];
|
||||||
}
|
}
|
||||||
|
|
||||||
const sendCreateBeerPostRequest = async (data: IFormInput) => {
|
|
||||||
// const body = JSON.stringify(data);
|
|
||||||
|
|
||||||
const response = await fetch('/api/beers/create', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify(data),
|
|
||||||
});
|
|
||||||
|
|
||||||
const json = await response.json();
|
|
||||||
|
|
||||||
console.log(json);
|
|
||||||
};
|
|
||||||
|
|
||||||
const BeerForm: FunctionComponent<BeerFormProps> = ({
|
const BeerForm: FunctionComponent<BeerFormProps> = ({
|
||||||
type,
|
formType,
|
||||||
defaultValues,
|
defaultValues,
|
||||||
breweries = [],
|
breweries = [],
|
||||||
types = [],
|
types = [],
|
||||||
@@ -51,7 +37,8 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
|||||||
register,
|
register,
|
||||||
handleSubmit,
|
handleSubmit,
|
||||||
formState: { errors },
|
formState: { errors },
|
||||||
} = useForm<IFormInput>({
|
} = useForm<BeerPostT>({
|
||||||
|
resolver: zodResolver(BeerPostValidationSchema),
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
name: defaultValues?.name,
|
name: defaultValues?.name,
|
||||||
description: defaultValues?.description,
|
description: defaultValues?.description,
|
||||||
@@ -60,47 +47,19 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// const navigate = useNavigate();
|
const onSubmit: SubmitHandler<BeerPostT> = async (data) => {
|
||||||
|
switch (formType) {
|
||||||
const nameValidationSchema = register('name', {
|
case 'create': {
|
||||||
required: 'Beer name is required.',
|
try {
|
||||||
});
|
const response = await sendCreateBeerPostRequest(data);
|
||||||
const breweryValidationSchema = register('breweryId', {
|
Router.push(`/beers/${response.id}`);
|
||||||
required: 'Brewery name is required.',
|
break;
|
||||||
});
|
} catch (e) {
|
||||||
const abvValidationSchema = register('abv', {
|
// eslint-disable-next-line no-console
|
||||||
required: 'ABV is required.',
|
console.error(e);
|
||||||
valueAsNumber: true,
|
break;
|
||||||
max: { value: 50, message: 'ABV must be less than 50%.' },
|
}
|
||||||
min: {
|
}
|
||||||
value: 0.1,
|
|
||||||
message: 'ABV must be greater than 0.1%',
|
|
||||||
},
|
|
||||||
validate: (abv) => !Number.isNaN(abv) || 'ABV is invalid.',
|
|
||||||
});
|
|
||||||
const ibuValidationSchema = register('ibu', {
|
|
||||||
required: 'IBU is required.',
|
|
||||||
min: {
|
|
||||||
value: 2,
|
|
||||||
message: 'IBU must be greater than 2.',
|
|
||||||
},
|
|
||||||
valueAsNumber: true,
|
|
||||||
validate: (ibu) => !Number.isNaN(ibu) || 'IBU is invalid.',
|
|
||||||
});
|
|
||||||
|
|
||||||
const descriptionValidationSchema = register('description', {
|
|
||||||
required: 'Description is required.',
|
|
||||||
});
|
|
||||||
|
|
||||||
const typeIdValidationSchema = register('typeId', {
|
|
||||||
required: 'Type is required.',
|
|
||||||
});
|
|
||||||
|
|
||||||
const onSubmit: SubmitHandler<IFormInput> = async (data) => {
|
|
||||||
switch (type) {
|
|
||||||
case 'create':
|
|
||||||
await sendCreateBeerPostRequest(data);
|
|
||||||
break;
|
|
||||||
case 'edit':
|
case 'edit':
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
@@ -117,13 +76,13 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
|||||||
<FormSegment>
|
<FormSegment>
|
||||||
<FormTextInput
|
<FormTextInput
|
||||||
placeholder="Lorem Ipsum Lager"
|
placeholder="Lorem Ipsum Lager"
|
||||||
formValidationSchema={nameValidationSchema}
|
formValidationSchema={register('name')}
|
||||||
error={!!errors.name}
|
error={!!errors.name}
|
||||||
type="text"
|
type="text"
|
||||||
id="name"
|
id="name"
|
||||||
/>
|
/>
|
||||||
</FormSegment>
|
</FormSegment>
|
||||||
{type === 'create' && breweries.length && (
|
{formType === 'create' && breweries.length && (
|
||||||
<>
|
<>
|
||||||
<FormInfo>
|
<FormInfo>
|
||||||
<FormLabel htmlFor="breweryId">Brewery</FormLabel>
|
<FormLabel htmlFor="breweryId">Brewery</FormLabel>
|
||||||
@@ -131,7 +90,7 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
|||||||
</FormInfo>
|
</FormInfo>
|
||||||
<FormSegment>
|
<FormSegment>
|
||||||
<FormSelect
|
<FormSelect
|
||||||
formRegister={breweryValidationSchema}
|
formRegister={register('breweryId')}
|
||||||
error={!!errors.breweryId}
|
error={!!errors.breweryId}
|
||||||
id="breweryId"
|
id="breweryId"
|
||||||
options={breweries.map((brewery) => ({
|
options={breweries.map((brewery) => ({
|
||||||
@@ -153,7 +112,7 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
|||||||
</FormInfo>
|
</FormInfo>
|
||||||
<FormTextInput
|
<FormTextInput
|
||||||
placeholder="12"
|
placeholder="12"
|
||||||
formValidationSchema={abvValidationSchema}
|
formValidationSchema={register('abv', { valueAsNumber: true })}
|
||||||
error={!!errors.abv}
|
error={!!errors.abv}
|
||||||
type="text"
|
type="text"
|
||||||
id="abv"
|
id="abv"
|
||||||
@@ -166,7 +125,7 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
|||||||
</FormInfo>
|
</FormInfo>
|
||||||
<FormTextInput
|
<FormTextInput
|
||||||
placeholder="52"
|
placeholder="52"
|
||||||
formValidationSchema={ibuValidationSchema}
|
formValidationSchema={register('ibu', { valueAsNumber: true })}
|
||||||
error={!!errors.ibu}
|
error={!!errors.ibu}
|
||||||
type="text"
|
type="text"
|
||||||
id="lastName"
|
id="lastName"
|
||||||
@@ -182,7 +141,7 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
|||||||
<FormTextArea
|
<FormTextArea
|
||||||
placeholder="Ratione cumque quas quia aut impedit ea culpa facere. Ut in sit et quas reiciendis itaque."
|
placeholder="Ratione cumque quas quia aut impedit ea culpa facere. Ut in sit et quas reiciendis itaque."
|
||||||
error={!!errors.description}
|
error={!!errors.description}
|
||||||
formValidationSchema={descriptionValidationSchema}
|
formValidationSchema={register('description')}
|
||||||
id="description"
|
id="description"
|
||||||
rows={8}
|
rows={8}
|
||||||
/>
|
/>
|
||||||
@@ -194,7 +153,7 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
|||||||
</FormInfo>
|
</FormInfo>
|
||||||
<FormSegment>
|
<FormSegment>
|
||||||
<FormSelect
|
<FormSelect
|
||||||
formRegister={typeIdValidationSchema}
|
formRegister={register('typeId')}
|
||||||
error={!!errors.typeId}
|
error={!!errors.typeId}
|
||||||
id="typeId"
|
id="typeId"
|
||||||
options={types.map((beerType) => ({
|
options={types.map((beerType) => ({
|
||||||
@@ -207,7 +166,7 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
|||||||
</FormSegment>
|
</FormSegment>
|
||||||
|
|
||||||
<Button type="submit">{`${
|
<Button type="submit">{`${
|
||||||
type === 'edit'
|
formType === 'edit'
|
||||||
? `Edit ${defaultValues?.name || 'beer post'}`
|
? `Edit ${defaultValues?.name || 'beer post'}`
|
||||||
: 'Create beer post'
|
: 'Create beer post'
|
||||||
} `}</Button>
|
} `}</Button>
|
||||||
|
|||||||
27
components/BeerIndex/BeerCard.tsx
Normal file
27
components/BeerIndex/BeerCard.tsx
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import BeerPostQueryResult from '@/services/BeerPost/types/BeerPostQueryResult';
|
||||||
|
import Link from 'next/link';
|
||||||
|
import { FC } from 'react';
|
||||||
|
import Image from 'next/image';
|
||||||
|
|
||||||
|
const BeerCard: FC<{ post: BeerPostQueryResult }> = ({ post }) => {
|
||||||
|
return (
|
||||||
|
<div className="card bg-base-300" key={post.id}>
|
||||||
|
<figure className="card-image h-96">
|
||||||
|
{post.beerImages.length > 0 && (
|
||||||
|
<Image src={post.beerImages[0].url} alt={post.name} width="1029" height="110" />
|
||||||
|
)}
|
||||||
|
</figure>
|
||||||
|
|
||||||
|
<div className="card-body space-y-3">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-3xl font-bold">
|
||||||
|
<Link href={`/beers/${post.id}`}>{post.name}</Link>
|
||||||
|
</h2>
|
||||||
|
<h3 className="text-xl font-semibold">{post.brewery.name}</h3>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default BeerCard;
|
||||||
37
components/BeerIndex/Pagination.tsx
Normal file
37
components/BeerIndex/Pagination.tsx
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { useRouter } from 'next/router';
|
||||||
|
import { FC } from 'react';
|
||||||
|
|
||||||
|
interface PaginationProps {
|
||||||
|
pageNum: number;
|
||||||
|
pageCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const Pagination: FC<PaginationProps> = ({ pageCount, pageNum }) => {
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="btn-group">
|
||||||
|
<button
|
||||||
|
className="btn"
|
||||||
|
disabled={pageNum <= 1}
|
||||||
|
onClick={async () =>
|
||||||
|
router.push({ pathname: '/beers', query: { page_num: pageNum - 1 } })
|
||||||
|
}
|
||||||
|
>
|
||||||
|
«
|
||||||
|
</button>
|
||||||
|
<button className="btn">Page {pageNum}</button>
|
||||||
|
<button
|
||||||
|
className="btn"
|
||||||
|
disabled={pageNum >= pageCount}
|
||||||
|
onClick={async () =>
|
||||||
|
router.push({ pathname: '/beers', query: { page_num: pageNum + 1 } })
|
||||||
|
}
|
||||||
|
>
|
||||||
|
»
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Pagination;
|
||||||
@@ -3,18 +3,13 @@ import { FunctionComponent } from 'react';
|
|||||||
interface FormButtonProps {
|
interface FormButtonProps {
|
||||||
children: string;
|
children: string;
|
||||||
type: 'button' | 'submit' | 'reset';
|
type: 'button' | 'submit' | 'reset';
|
||||||
className?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const Button: FunctionComponent<FormButtonProps> = ({ children, type, className }) => (
|
const Button: FunctionComponent<FormButtonProps> = ({ children, type }) => (
|
||||||
// eslint-disable-next-line react/button-has-type
|
// eslint-disable-next-line react/button-has-type
|
||||||
<button type={type} className="btn-primary btn mt-4 w-full rounded-xl">
|
<button type={type} className="btn-primary btn mt-4 w-full rounded-xl">
|
||||||
{children}
|
{children}
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
|
|
||||||
Button.defaultProps = {
|
|
||||||
className: '',
|
|
||||||
};
|
|
||||||
|
|
||||||
export default Button;
|
export default Button;
|
||||||
@@ -3,8 +3,6 @@ import { FunctionComponent } from 'react';
|
|||||||
// import { faTriangleExclamation } from '@fortawesome/free-solid-svg-icons';
|
// import { faTriangleExclamation } from '@fortawesome/free-solid-svg-icons';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Component for a styled form error message.
|
|
||||||
*
|
|
||||||
* @example
|
* @example
|
||||||
* <FormError>Something went wrong!</FormError>;
|
* <FormError>Something went wrong!</FormError>;
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -1,10 +1,16 @@
|
|||||||
import { FunctionComponent, ReactNode } from 'react';
|
import { FunctionComponent, ReactNode } from 'react';
|
||||||
|
|
||||||
/** A container for both the form error and form label. */
|
|
||||||
interface FormInfoProps {
|
interface FormInfoProps {
|
||||||
children: Array<ReactNode> | ReactNode;
|
children: [ReactNode, ReactNode];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @example
|
||||||
|
* <FormInfo>
|
||||||
|
* <FormLabel htmlFor="name">Name</FormLabel>
|
||||||
|
* <FormError>{errors.name?.message}</FormError>
|
||||||
|
* </FormInfo>;
|
||||||
|
*/
|
||||||
const FormInfo: FunctionComponent<FormInfoProps> = ({ children }) => (
|
const FormInfo: FunctionComponent<FormInfoProps> = ({ children }) => (
|
||||||
<div className="flex justify-between">{children}</div>
|
<div className="flex justify-between">{children}</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -5,9 +5,13 @@ interface FormLabelProps {
|
|||||||
children: string;
|
children: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @example
|
||||||
|
* <FormLabel htmlFor="name">Name</FormLabel>;
|
||||||
|
*/
|
||||||
const FormLabel: FunctionComponent<FormLabelProps> = ({ htmlFor, children }) => (
|
const FormLabel: FunctionComponent<FormLabelProps> = ({ htmlFor, children }) => (
|
||||||
<label
|
<label
|
||||||
className="block uppercase tracking-wide text-sm sm:text-xs font-extrabold my-1"
|
className="my-1 block text-sm font-extrabold uppercase tracking-wide sm:text-xs"
|
||||||
htmlFor={htmlFor}
|
htmlFor={htmlFor}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
|
|||||||
@@ -10,6 +10,29 @@ interface FormSelectProps {
|
|||||||
message: string;
|
message: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @example
|
||||||
|
* <FormSelect
|
||||||
|
* options={[
|
||||||
|
* { value: '1', text: 'One' },
|
||||||
|
* { value: '2', text: 'Two' },
|
||||||
|
* { value: '3', text: 'Three' },
|
||||||
|
* ]}
|
||||||
|
* id="test"
|
||||||
|
* formRegister={register('test')}
|
||||||
|
* error={true}
|
||||||
|
* placeholder="Test"
|
||||||
|
* message="Select an option"
|
||||||
|
* />;
|
||||||
|
*
|
||||||
|
* @param props
|
||||||
|
* @param props.options The options to display in the select.
|
||||||
|
* @param props.id The id of the select.
|
||||||
|
* @param props.formRegister The form register hook from react-hook-form.
|
||||||
|
* @param props.error Whether or not the select has an error.
|
||||||
|
* @param props.placeholder The placeholder text for the select.
|
||||||
|
* @param props.message The message to display when no option is selected.
|
||||||
|
*/
|
||||||
const FormSelect: FunctionComponent<FormSelectProps> = ({
|
const FormSelect: FunctionComponent<FormSelectProps> = ({
|
||||||
options,
|
options,
|
||||||
id,
|
id,
|
||||||
@@ -20,7 +43,7 @@ const FormSelect: FunctionComponent<FormSelectProps> = ({
|
|||||||
}) => (
|
}) => (
|
||||||
<select
|
<select
|
||||||
id={id}
|
id={id}
|
||||||
className={`select select-bordered block w-full rounded-lg ${
|
className={`select-bordered select block w-full rounded-lg ${
|
||||||
error ? 'select-error' : ''
|
error ? 'select-error' : ''
|
||||||
}`}
|
}`}
|
||||||
placeholder={placeholder}
|
placeholder={placeholder}
|
||||||
|
|||||||
@@ -7,21 +7,36 @@ interface FormTextAreaProps {
|
|||||||
error: boolean;
|
error: boolean;
|
||||||
id: string;
|
id: string;
|
||||||
rows: number;
|
rows: number;
|
||||||
className?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @example
|
||||||
|
* <FormTextArea
|
||||||
|
* id="test"
|
||||||
|
* formValidationSchema={register('test')}
|
||||||
|
* error={true}
|
||||||
|
* placeholder="Test"
|
||||||
|
* rows={5}
|
||||||
|
* />;
|
||||||
|
*
|
||||||
|
* @param props
|
||||||
|
* @param props.placeholder The placeholder text for the textarea.
|
||||||
|
* @param props.formValidationSchema The form register hook from react-hook-form.
|
||||||
|
* @param props.error Whether or not the textarea has an error.
|
||||||
|
* @param props.id The id of the textarea.
|
||||||
|
* @param props.rows The number of rows to display in the textarea.
|
||||||
|
*/
|
||||||
const FormTextArea: FunctionComponent<FormTextAreaProps> = ({
|
const FormTextArea: FunctionComponent<FormTextAreaProps> = ({
|
||||||
placeholder = '',
|
placeholder = '',
|
||||||
formValidationSchema,
|
formValidationSchema,
|
||||||
error,
|
error,
|
||||||
id,
|
id,
|
||||||
rows,
|
rows,
|
||||||
className,
|
|
||||||
}) => (
|
}) => (
|
||||||
<textarea
|
<textarea
|
||||||
id={id}
|
id={id}
|
||||||
placeholder={placeholder}
|
placeholder={placeholder}
|
||||||
className={`${className} textarea textarea-bordered w-full resize-none rounded-lg bg-clip-padding border border-solid transition ease-in-out m-0 ${
|
className={`textarea-bordered textarea m-0 w-full resize-none rounded-lg border border-solid bg-clip-padding transition ease-in-out ${
|
||||||
error ? 'textarea-error' : ''
|
error ? 'textarea-error' : ''
|
||||||
}`}
|
}`}
|
||||||
{...formValidationSchema}
|
{...formValidationSchema}
|
||||||
@@ -29,9 +44,4 @@ const FormTextArea: FunctionComponent<FormTextAreaProps> = ({
|
|||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|
||||||
FormTextArea.defaultProps = {
|
|
||||||
placeholder: '',
|
|
||||||
className: '',
|
|
||||||
};
|
|
||||||
|
|
||||||
export default FormTextArea;
|
export default FormTextArea;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
/* eslint-disable react/require-default-props */
|
/* eslint-disable react/require-default-props */
|
||||||
import { FunctionComponent } from 'react';
|
import { FunctionComponent } from 'react';
|
||||||
import { FieldError, UseFormRegisterReturn } from 'react-hook-form';
|
import { UseFormRegisterReturn } from 'react-hook-form';
|
||||||
|
|
||||||
interface FormInputProps {
|
interface FormInputProps {
|
||||||
placeholder?: string;
|
placeholder?: string;
|
||||||
@@ -12,6 +12,25 @@ interface FormInputProps {
|
|||||||
height?: string;
|
height?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @example
|
||||||
|
* <FormTextInput
|
||||||
|
* placeholder="Lorem Ipsum Lager"
|
||||||
|
* formValidationSchema={register('name')}
|
||||||
|
* error={!!errors.name}
|
||||||
|
* type="text"
|
||||||
|
* id="name"
|
||||||
|
* />;
|
||||||
|
*
|
||||||
|
* @param param0 The props for the FormTextInput component
|
||||||
|
* @param param0.placeholder The placeholder text for the input
|
||||||
|
* @param param0.formValidationSchema The validation schema for the input, provided by
|
||||||
|
* react-hook-form.
|
||||||
|
* @param param0.error Whether or not the input has an error.
|
||||||
|
* @param param0.type The input type (email, password, text, date).
|
||||||
|
* @param param0.id The id of the input.
|
||||||
|
* @param param0.height The height of the input.
|
||||||
|
*/
|
||||||
const FormTextInput: FunctionComponent<FormInputProps> = ({
|
const FormTextInput: FunctionComponent<FormInputProps> = ({
|
||||||
placeholder = '',
|
placeholder = '',
|
||||||
formValidationSchema,
|
formValidationSchema,
|
||||||
@@ -23,7 +42,7 @@ const FormTextInput: FunctionComponent<FormInputProps> = ({
|
|||||||
id={id}
|
id={id}
|
||||||
type={type}
|
type={type}
|
||||||
placeholder={placeholder}
|
placeholder={placeholder}
|
||||||
className={`input w-full transition ease-in-out rounded-lg input-bordered ${
|
className={`input-bordered input w-full rounded-lg transition ease-in-out ${
|
||||||
error ? 'input-error' : ''
|
error ? 'input-error' : ''
|
||||||
}`}
|
}`}
|
||||||
{...formValidationSchema}
|
{...formValidationSchema}
|
||||||
|
|||||||
1031
package-lock.json
generated
1031
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
19
package.json
19
package.json
@@ -16,36 +16,35 @@
|
|||||||
"@hookform/resolvers": "^2.9.10",
|
"@hookform/resolvers": "^2.9.10",
|
||||||
"@next/font": "13.1.2",
|
"@next/font": "13.1.2",
|
||||||
"@prisma/client": "^4.8.1",
|
"@prisma/client": "^4.8.1",
|
||||||
"@types/node": "18.11.18",
|
|
||||||
"@types/react": "18.0.26",
|
|
||||||
"@types/react-dom": "18.0.10",
|
|
||||||
"daisyui": "^2.47.0",
|
|
||||||
"date-fns": "^2.29.3",
|
"date-fns": "^2.29.3",
|
||||||
"eslint": "8.32.0",
|
|
||||||
"eslint-config-next": "13.1.2",
|
|
||||||
"next": "13.1.2",
|
"next": "13.1.2",
|
||||||
"pino": "^8.8.0",
|
|
||||||
"pino-pretty": "^9.1.1",
|
"pino-pretty": "^9.1.1",
|
||||||
"react": "18.2.0",
|
"pino": "^8.8.0",
|
||||||
"react-dom": "18.2.0",
|
"react-dom": "18.2.0",
|
||||||
"react-hook-form": "^7.42.1",
|
"react-hook-form": "^7.42.1",
|
||||||
"react-icons": "^4.7.1",
|
"react-icons": "^4.7.1",
|
||||||
|
"react": "18.2.0",
|
||||||
"typescript": "4.9.4",
|
"typescript": "4.9.4",
|
||||||
"zod": "^3.20.2"
|
"zod": "^3.20.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@faker-js/faker": "^7.6.0",
|
"@faker-js/faker": "^7.6.0",
|
||||||
|
"@types/node": "18.11.18",
|
||||||
|
"@types/react-dom": "18.0.10",
|
||||||
|
"@types/react": "18.0.26",
|
||||||
"autoprefixer": "^10.4.13",
|
"autoprefixer": "^10.4.13",
|
||||||
|
"daisyui": "^2.47.0",
|
||||||
"dotenv-cli": "^6.0.0",
|
"dotenv-cli": "^6.0.0",
|
||||||
"eslint": "^8.30.0",
|
|
||||||
"eslint-config-airbnb-base": "15.0.0",
|
"eslint-config-airbnb-base": "15.0.0",
|
||||||
"eslint-config-airbnb-typescript": "17.0.0",
|
"eslint-config-airbnb-typescript": "17.0.0",
|
||||||
"eslint-config-next": "^13.0.7",
|
"eslint-config-next": "^13.0.7",
|
||||||
"eslint-config-prettier": "^8.3.0",
|
"eslint-config-prettier": "^8.3.0",
|
||||||
"eslint-plugin-react": "^7.31.11",
|
"eslint-plugin-react": "^7.31.11",
|
||||||
|
"eslint": "8.32.0",
|
||||||
"postcss": "^8.4.21",
|
"postcss": "^8.4.21",
|
||||||
"prettier": "^2.8.1",
|
"prettier-plugin-jsdoc": "^0.4.2",
|
||||||
"prettier-plugin-tailwindcss": "^0.2.1",
|
"prettier-plugin-tailwindcss": "^0.2.1",
|
||||||
|
"prettier": "^2.8.1",
|
||||||
"prisma": "^4.8.1",
|
"prisma": "^4.8.1",
|
||||||
"tailwindcss": "^3.2.4",
|
"tailwindcss": "^3.2.4",
|
||||||
"ts-node": "^10.9.1"
|
"ts-node": "^10.9.1"
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
|
import BeerPostValidationSchema from '@/validation/BeerPostValidationSchema';
|
||||||
import DBClient from '@/prisma/DBClient';
|
import DBClient from '@/prisma/DBClient';
|
||||||
import { NextApiHandler } from 'next';
|
import { NextApiHandler } from 'next';
|
||||||
|
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||||
|
|
||||||
class ServerError extends Error {
|
class ServerError extends Error {
|
||||||
constructor(message: string, public statusCode: number) {
|
constructor(message: string, public statusCode: number) {
|
||||||
@@ -9,23 +12,10 @@ class ServerError extends Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const NewBeerInfo = z.object({
|
const handler: NextApiHandler<z.infer<typeof APIResponseValidationSchema>> = async (
|
||||||
name: z.string().min(1).max(100),
|
req,
|
||||||
description: z.string().min(1).max(1000),
|
res,
|
||||||
typeId: z.string().uuid(),
|
) => {
|
||||||
abv: z.number().min(1).max(50),
|
|
||||||
ibu: z.number().min(2),
|
|
||||||
breweryId: z.string().uuid(),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const ResponseBody = z.object({
|
|
||||||
message: z.string(),
|
|
||||||
statusCode: z.number(),
|
|
||||||
success: z.boolean(),
|
|
||||||
payload: z.unknown(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const handler: NextApiHandler<z.infer<typeof ResponseBody>> = async (req, res) => {
|
|
||||||
try {
|
try {
|
||||||
const { method } = req;
|
const { method } = req;
|
||||||
|
|
||||||
@@ -33,14 +23,12 @@ const handler: NextApiHandler<z.infer<typeof ResponseBody>> = async (req, res) =
|
|||||||
throw new ServerError('Method not allowed', 405);
|
throw new ServerError('Method not allowed', 405);
|
||||||
}
|
}
|
||||||
|
|
||||||
const cleanedReqBody = NewBeerInfo.safeParse(req.body);
|
const cleanedReqBody = BeerPostValidationSchema.safeParse(req.body);
|
||||||
|
|
||||||
if (!cleanedReqBody.success) {
|
if (!cleanedReqBody.success) {
|
||||||
throw new ServerError('Invalid request body', 400);
|
throw new ServerError('Invalid request body', 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
const { name, description, typeId, abv, ibu, breweryId } = cleanedReqBody.data;
|
const { name, description, typeId, abv, ibu, breweryId } = cleanedReqBody.data;
|
||||||
|
|
||||||
const user = await DBClient.instance.user.findFirstOrThrow();
|
const user = await DBClient.instance.user.findFirstOrThrow();
|
||||||
|
|
||||||
const newBeerPost = await DBClient.instance.beerPost.create({
|
const newBeerPost = await DBClient.instance.beerPost.create({
|
||||||
@@ -67,9 +55,12 @@ const handler: NextApiHandler<z.infer<typeof ResponseBody>> = async (req, res) =
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
res
|
res.status(201).json({
|
||||||
.status(200)
|
message: 'Beer post created successfully',
|
||||||
.json({ message: 'Success', statusCode: 200, payload: newBeerPost, success: true });
|
statusCode: 201,
|
||||||
|
payload: newBeerPost,
|
||||||
|
success: true,
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof ServerError) {
|
if (error instanceof ServerError) {
|
||||||
res.status(error.statusCode).json({
|
res.status(error.statusCode).json({
|
||||||
|
|||||||
@@ -1,110 +1,18 @@
|
|||||||
import { GetServerSideProps, NextPage } from 'next';
|
import { GetServerSideProps, NextPage } from 'next';
|
||||||
import BeerPostQueryResult from '@/services/BeerPost/types/BeerPostQueryResult';
|
import BeerPostQueryResult from '@/services/BeerPost/types/BeerPostQueryResult';
|
||||||
import getBeerPostById from '@/services/BeerPost/getBeerPostById';
|
import getBeerPostById from '@/services/BeerPost/getBeerPostById';
|
||||||
import Layout from '@/components/Layout';
|
import Layout from '@/components/ui/Layout';
|
||||||
import Head from 'next/head';
|
import Head from 'next/head';
|
||||||
import Link from 'next/link';
|
|
||||||
import formatDistanceStrict from 'date-fns/formatDistanceStrict';
|
|
||||||
import { useState } from 'react';
|
|
||||||
|
|
||||||
import { FaRegThumbsUp, FaThumbsUp } from 'react-icons/fa';
|
import Image from 'next/image';
|
||||||
|
import BeerInfoHeader from '@/components/BeerById/BeerInfoHeader';
|
||||||
|
import CommentCard from '@/components/BeerById/CommentCard';
|
||||||
|
|
||||||
interface BeerPageProps {
|
interface BeerPageProps {
|
||||||
beerPost: BeerPostQueryResult;
|
beerPost: BeerPostQueryResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
const BeerInfoHeader: React.FC<{ beerPost: BeerPostQueryResult }> = ({ beerPost }) => {
|
|
||||||
const createdAtDate = new Date(beerPost.createdAt);
|
|
||||||
const timeDistance = formatDistanceStrict(createdAtDate, Date.now());
|
|
||||||
|
|
||||||
const [isLiked, setIsLiked] = useState(false);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="card bg-base-300">
|
|
||||||
<div className="card-body">
|
|
||||||
<h1 className="text-4xl font-bold">{beerPost.name}</h1>
|
|
||||||
<h2 className="text-2xl font-semibold">
|
|
||||||
by{' '}
|
|
||||||
<Link
|
|
||||||
href={`/breweries/${beerPost.brewery.id}`}
|
|
||||||
className="link-hover link text-2xl font-semibold"
|
|
||||||
>
|
|
||||||
{beerPost.brewery.name}
|
|
||||||
</Link>
|
|
||||||
</h2>
|
|
||||||
|
|
||||||
<h3 className="italic">
|
|
||||||
posted by{' '}
|
|
||||||
<Link href={`/users/${beerPost.postedBy.id}`} className="link-hover link">
|
|
||||||
{beerPost.postedBy.username}
|
|
||||||
</Link>
|
|
||||||
{` ${timeDistance}`} ago
|
|
||||||
</h3>
|
|
||||||
|
|
||||||
<p>{beerPost.description}</p>
|
|
||||||
<div className="flex justify-between">
|
|
||||||
<div>
|
|
||||||
<div className="mb-1">
|
|
||||||
<Link
|
|
||||||
className="text-lg font-medium"
|
|
||||||
href={`/beers/types/${beerPost.type.id}`}
|
|
||||||
>
|
|
||||||
{beerPost.type.name}
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<span className="mr-4 text-lg font-medium">{beerPost.abv}% ABV</span>
|
|
||||||
<span className="text-lg font-medium">{beerPost.ibu} IBU</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="card-actions">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className={`btn gap-2 rounded-2xl ${
|
|
||||||
!isLiked ? 'btn-ghost outline' : 'btn-primary'
|
|
||||||
}`}
|
|
||||||
onClick={() => {
|
|
||||||
setIsLiked(!isLiked);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{isLiked ? (
|
|
||||||
<>
|
|
||||||
<FaThumbsUp className="text-2xl" />
|
|
||||||
<span>Liked</span>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<FaRegThumbsUp className="text-2xl" />
|
|
||||||
<span>Like</span>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const CommentCard: React.FC<{ comment: BeerPostQueryResult['beerComments'][number] }> = ({
|
|
||||||
comment,
|
|
||||||
}) => {
|
|
||||||
return (
|
|
||||||
<div className="card bg-base-300">
|
|
||||||
<div className="card-body">
|
|
||||||
<h3 className="text-2xl font-semibold">{comment.postedBy.username}</h3>
|
|
||||||
<h4 className="italic">{`posted ${formatDistanceStrict(
|
|
||||||
new Date(comment.createdAt),
|
|
||||||
new Date(),
|
|
||||||
)} ago`}</h4>
|
|
||||||
<p>{comment.content}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const BeerByIdPage: NextPage<BeerPageProps> = ({ beerPost }) => {
|
const BeerByIdPage: NextPage<BeerPageProps> = ({ beerPost }) => {
|
||||||
console.log(beerPost.beerComments);
|
|
||||||
return (
|
return (
|
||||||
<Layout>
|
<Layout>
|
||||||
<Head>
|
<Head>
|
||||||
@@ -113,7 +21,8 @@ const BeerByIdPage: NextPage<BeerPageProps> = ({ beerPost }) => {
|
|||||||
</Head>
|
</Head>
|
||||||
<main>
|
<main>
|
||||||
{beerPost.beerImages[0] && (
|
{beerPost.beerImages[0] && (
|
||||||
<img
|
<Image
|
||||||
|
alt={beerPost.beerImages[0].alt}
|
||||||
src={beerPost.beerImages[0].url}
|
src={beerPost.beerImages[0].url}
|
||||||
className="h-[42rem] w-full object-cover"
|
className="h-[42rem] w-full object-cover"
|
||||||
/>
|
/>
|
||||||
@@ -122,13 +31,10 @@ const BeerByIdPage: NextPage<BeerPageProps> = ({ beerPost }) => {
|
|||||||
<div className="my-12 flex w-full items-center justify-center ">
|
<div className="my-12 flex w-full items-center justify-center ">
|
||||||
<div className="w-10/12 space-y-3">
|
<div className="w-10/12 space-y-3">
|
||||||
<BeerInfoHeader beerPost={beerPost} />
|
<BeerInfoHeader beerPost={beerPost} />
|
||||||
|
|
||||||
<div className="mt-4 flex space-x-3">
|
<div className="mt-4 flex space-x-3">
|
||||||
<div className="w-[60%] space-y-3">
|
<div className="w-[60%] space-y-3">
|
||||||
<div className="card h-[22rem] bg-base-300"></div>
|
<div className="card h-[22rem] bg-base-300"></div>
|
||||||
<div className="card h-[44rem] overflow-y-auto bg-base-300">
|
<div className="card h-[44rem] overflow-y-auto bg-base-300">
|
||||||
{/* for each comment make a card */}
|
|
||||||
|
|
||||||
{beerPost.beerComments.map((comment) => (
|
{beerPost.beerComments.map((comment) => (
|
||||||
<CommentCard key={comment.id} comment={comment} />
|
<CommentCard key={comment.id} comment={comment} />
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import BeerForm from '@/components/BeerForm';
|
import BeerForm from '@/components/BeerForm';
|
||||||
import Layout from '@/components/Layout';
|
import Layout from '@/components/ui/Layout';
|
||||||
import DBClient from '@/prisma/DBClient';
|
import DBClient from '@/prisma/DBClient';
|
||||||
import getAllBreweryPosts from '@/services/BreweryPost/getAllBreweryPosts';
|
import getAllBreweryPosts from '@/services/BreweryPost/getAllBreweryPosts';
|
||||||
import BreweryPostQueryResult from '@/services/BreweryPost/types/BreweryPostQueryResult';
|
import BreweryPostQueryResult from '@/services/BreweryPost/types/BreweryPostQueryResult';
|
||||||
@@ -16,14 +16,13 @@ interface CreateBeerPageProps {
|
|||||||
const Create: NextPage<CreateBeerPageProps> = ({ breweries, types }) => {
|
const Create: NextPage<CreateBeerPageProps> = ({ breweries, types }) => {
|
||||||
return (
|
return (
|
||||||
<Layout>
|
<Layout>
|
||||||
<div className="align-center my-12 flex h-full flex-col items-center justify-center">
|
<div className="align-center my-20 flex h-fit flex-col items-center justify-center">
|
||||||
<div className="w-8/12">
|
<div className="w-8/12">
|
||||||
<div className="flex flex-col items-center space-y-1">
|
<div className="flex flex-col items-center space-y-1">
|
||||||
<BiBeer className="text-5xl" />
|
<BiBeer className="text-5xl" />
|
||||||
<h1 className="text-3xl font-bold">Create a New Beer</h1>
|
<h1 className="text-3xl font-bold">Create a New Beer</h1>
|
||||||
</div>
|
</div>
|
||||||
|
<BeerForm formType="create" breweries={breweries} types={types} />
|
||||||
<BeerForm type="create" breweries={breweries} types={types} />
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Layout>
|
</Layout>
|
||||||
@@ -32,8 +31,8 @@ const Create: NextPage<CreateBeerPageProps> = ({ breweries, types }) => {
|
|||||||
|
|
||||||
export const getServerSideProps = async () => {
|
export const getServerSideProps = async () => {
|
||||||
const breweryPosts = await getAllBreweryPosts();
|
const breweryPosts = await getAllBreweryPosts();
|
||||||
|
|
||||||
const beerTypes = await DBClient.instance.beerType.findMany();
|
const beerTypes = await DBClient.instance.beerType.findMany();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
props: {
|
props: {
|
||||||
breweries: JSON.parse(JSON.stringify(breweryPosts)),
|
breweries: JSON.parse(JSON.stringify(breweryPosts)),
|
||||||
|
|||||||
@@ -1,75 +1,18 @@
|
|||||||
import { GetServerSideProps, NextPage } from 'next';
|
import { GetServerSideProps, NextPage } from 'next';
|
||||||
import getAllBeerPosts from '@/services/BeerPost/getAllBeerPosts';
|
import getAllBeerPosts from '@/services/BeerPost/getAllBeerPosts';
|
||||||
import BeerPostQueryResult from '@/services/BeerPost/types/BeerPostQueryResult';
|
import BeerPostQueryResult from '@/services/BeerPost/types/BeerPostQueryResult';
|
||||||
import Link from 'next/link';
|
|
||||||
|
|
||||||
import { useRouter } from 'next/router';
|
import { useRouter } from 'next/router';
|
||||||
import DBClient from '@/prisma/DBClient';
|
import DBClient from '@/prisma/DBClient';
|
||||||
import Layout from '@/components/Layout';
|
import Layout from '@/components/ui/Layout';
|
||||||
import { FC } from 'react';
|
import Pagination from '../../components/BeerIndex/Pagination';
|
||||||
import Image from 'next/image';
|
import BeerCard from '../../components/BeerIndex/BeerCard';
|
||||||
|
|
||||||
interface BeerPageProps {
|
interface BeerPageProps {
|
||||||
initialBeerPosts: BeerPostQueryResult[];
|
initialBeerPosts: BeerPostQueryResult[];
|
||||||
pageCount: number;
|
pageCount: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface PaginationProps {
|
|
||||||
pageNum: number;
|
|
||||||
pageCount: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
const Pagination: FC<PaginationProps> = ({ pageCount, pageNum }) => {
|
|
||||||
const router = useRouter();
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="btn-group">
|
|
||||||
<button
|
|
||||||
className="btn"
|
|
||||||
disabled={pageNum <= 1}
|
|
||||||
onClick={async () =>
|
|
||||||
router.push({ pathname: '/beers', query: { page_num: pageNum - 1 } })
|
|
||||||
}
|
|
||||||
>
|
|
||||||
«
|
|
||||||
</button>
|
|
||||||
<button className="btn">Page {pageNum}</button>
|
|
||||||
<button
|
|
||||||
className="btn"
|
|
||||||
disabled={pageNum >= pageCount}
|
|
||||||
onClick={async () =>
|
|
||||||
router.push({ pathname: '/beers', query: { page_num: pageNum + 1 } })
|
|
||||||
}
|
|
||||||
>
|
|
||||||
»
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const BeerCard: FC<{ post: BeerPostQueryResult }> = ({ post }) => {
|
|
||||||
return (
|
|
||||||
<div className="card bg-base-300" key={post.id}>
|
|
||||||
<figure className="card-image h-96">
|
|
||||||
{post.beerImages.length > 0 && (
|
|
||||||
<Image src={post.beerImages[0].url} alt={post.name} width="1029" height="110" />
|
|
||||||
)}
|
|
||||||
</figure>
|
|
||||||
|
|
||||||
<div className="card-body space-y-3">
|
|
||||||
<div>
|
|
||||||
<h2 className="text-3xl font-bold">
|
|
||||||
<Link href={`/beers/${post.id}`}>{post.name}</Link>
|
|
||||||
</h2>
|
|
||||||
<h3 className="text-xl font-semibold">{post.brewery.name}</h3>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p>{post.description}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
const BeerPage: NextPage<BeerPageProps> = ({ initialBeerPosts, pageCount }) => {
|
const BeerPage: NextPage<BeerPageProps> = ({ initialBeerPosts, pageCount }) => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { query } = router;
|
const { query } = router;
|
||||||
@@ -93,13 +36,10 @@ const BeerPage: NextPage<BeerPageProps> = ({ initialBeerPosts, pageCount }) => {
|
|||||||
|
|
||||||
export const getServerSideProps: GetServerSideProps<BeerPageProps> = async (context) => {
|
export const getServerSideProps: GetServerSideProps<BeerPageProps> = async (context) => {
|
||||||
const { query } = context;
|
const { query } = context;
|
||||||
|
|
||||||
const pageNumber = parseInt(query.page_num as string, 10) || 1;
|
const pageNumber = parseInt(query.page_num as string, 10) || 1;
|
||||||
|
|
||||||
const pageSize = 12;
|
const pageSize = 12;
|
||||||
const numberOfPosts = await DBClient.instance.beerPost.count();
|
const numberOfPosts = await DBClient.instance.beerPost.count();
|
||||||
const pageCount = numberOfPosts ? Math.ceil(numberOfPosts / pageSize) : 0;
|
const pageCount = numberOfPosts ? Math.ceil(numberOfPosts / pageSize) : 0;
|
||||||
|
|
||||||
const beerPosts = await getAllBeerPosts(pageNumber, pageSize);
|
const beerPosts = await getAllBeerPosts(pageNumber, pageSize);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
12
prisma/migrations/20230127095307_/migration.sql
Normal file
12
prisma/migrations/20230127095307_/migration.sql
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
/*
|
||||||
|
Warnings:
|
||||||
|
|
||||||
|
- Added the required column `alt` to the `BeerImage` table without a default value. This is not possible if the table is not empty.
|
||||||
|
- Added the required column `alt` to the `BreweryImage` table without a default value. This is not possible if the table is not empty.
|
||||||
|
|
||||||
|
*/
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "BeerImage" ADD COLUMN "alt" TEXT NOT NULL;
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "BreweryImage" ADD COLUMN "alt" TEXT NOT NULL;
|
||||||
@@ -95,6 +95,7 @@ model BeerImage {
|
|||||||
beerPost BeerPost @relation(fields: [beerPostId], references: [id], onDelete: Cascade)
|
beerPost BeerPost @relation(fields: [beerPostId], references: [id], onDelete: Cascade)
|
||||||
beerPostId String
|
beerPostId String
|
||||||
url String
|
url String
|
||||||
|
alt String
|
||||||
createdAt DateTime @default(now()) @db.Timestamptz(3)
|
createdAt DateTime @default(now()) @db.Timestamptz(3)
|
||||||
updatedAt DateTime? @updatedAt @db.Timestamptz(3)
|
updatedAt DateTime? @updatedAt @db.Timestamptz(3)
|
||||||
}
|
}
|
||||||
@@ -106,4 +107,5 @@ model BreweryImage {
|
|||||||
url String
|
url String
|
||||||
createdAt DateTime @default(now()) @db.Timestamptz(3)
|
createdAt DateTime @default(now()) @db.Timestamptz(3)
|
||||||
updatedAt DateTime? @updatedAt @db.Timestamptz(3)
|
updatedAt DateTime? @updatedAt @db.Timestamptz(3)
|
||||||
|
alt String
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ const createNewBeerImages = async ({
|
|||||||
prisma.beerImage.create({
|
prisma.beerImage.create({
|
||||||
data: {
|
data: {
|
||||||
url: 'https://picsum.photos/900/1600',
|
url: 'https://picsum.photos/900/1600',
|
||||||
|
alt: 'Placeholder beer image.',
|
||||||
beerPost: { connect: { id: beerPost.id } },
|
beerPost: { connect: { id: beerPost.id } },
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ const createNewBreweryImages = async ({
|
|||||||
prisma.breweryImage.create({
|
prisma.breweryImage.create({
|
||||||
data: {
|
data: {
|
||||||
url: 'https://picsum.photos/900/1600',
|
url: 'https://picsum.photos/900/1600',
|
||||||
|
alt: 'Placeholder brewery image.',
|
||||||
breweryPost: { connect: { id: breweryPost.id } },
|
breweryPost: { connect: { id: breweryPost.id } },
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -33,11 +33,11 @@ import createNewUsers from './create/createNewUsers';
|
|||||||
});
|
});
|
||||||
const [beerPostComments, breweryPostComments] = await Promise.all([
|
const [beerPostComments, breweryPostComments] = await Promise.all([
|
||||||
createNewBeerPostComments({
|
createNewBeerPostComments({
|
||||||
numberOfComments: 1000,
|
numberOfComments: 500,
|
||||||
joinData: { beerPosts, users },
|
joinData: { beerPosts, users },
|
||||||
}),
|
}),
|
||||||
createNewBreweryPostComments({
|
createNewBreweryPostComments({
|
||||||
numberOfComments: 1000,
|
numberOfComments: 500,
|
||||||
joinData: { breweryPosts, users },
|
joinData: { breweryPosts, users },
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
|
|||||||
40
requests/sendCreateBeerPostRequest.ts
Normal file
40
requests/sendCreateBeerPostRequest.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import BeerPostValidationSchema from '@/validation/BeerPostValidationSchema';
|
||||||
|
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
const sendCreateBeerPostRequest = async (
|
||||||
|
data: z.infer<typeof BeerPostValidationSchema>,
|
||||||
|
) => {
|
||||||
|
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 } = parsed.data;
|
||||||
|
|
||||||
|
if (
|
||||||
|
!(
|
||||||
|
payload &&
|
||||||
|
typeof payload === 'object' &&
|
||||||
|
'id' in payload &&
|
||||||
|
typeof payload.id === 'string'
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
throw new Error('Invalid API response');
|
||||||
|
}
|
||||||
|
|
||||||
|
return payload;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default sendCreateBeerPostRequest;
|
||||||
@@ -32,7 +32,6 @@ const getAllBeerPosts = async (pageNum: number, pageSize: number) => {
|
|||||||
username: true,
|
username: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
beerComments: {
|
beerComments: {
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
@@ -46,11 +45,11 @@ const getAllBeerPosts = async (pageNum: number, pageSize: number) => {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
beerImages: {
|
beerImages: {
|
||||||
select: {
|
select: {
|
||||||
url: true,
|
url: true,
|
||||||
id: true,
|
id: true,
|
||||||
|
alt: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ const getBeerPostById = async (id: string) => {
|
|||||||
},
|
},
|
||||||
beerImages: {
|
beerImages: {
|
||||||
select: {
|
select: {
|
||||||
|
alt: true,
|
||||||
url: true,
|
url: true,
|
||||||
id: true,
|
id: true,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ export default interface BeerPostQueryResult {
|
|||||||
beerImages: {
|
beerImages: {
|
||||||
url: string;
|
url: string;
|
||||||
id: string;
|
id: string;
|
||||||
|
alt: string;
|
||||||
}[];
|
}[];
|
||||||
|
|
||||||
ibu: number;
|
ibu: number;
|
||||||
@@ -21,7 +22,6 @@ export default interface BeerPostQueryResult {
|
|||||||
id: string;
|
id: string;
|
||||||
username: string;
|
username: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
beerComments: {
|
beerComments: {
|
||||||
id: string;
|
id: string;
|
||||||
content: string;
|
content: string;
|
||||||
|
|||||||
10
validation/APIResponseValidationSchema.ts
Normal file
10
validation/APIResponseValidationSchema.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
const APIResponseValidationSchema = z.object({
|
||||||
|
message: z.string(),
|
||||||
|
statusCode: z.number(),
|
||||||
|
success: z.boolean(),
|
||||||
|
payload: z.unknown(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export default APIResponseValidationSchema;
|
||||||
43
validation/BeerPostValidationSchema.ts
Normal file
43
validation/BeerPostValidationSchema.ts
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
const BeerPostValidationSchema = z.object({
|
||||||
|
name: z
|
||||||
|
.string({
|
||||||
|
required_error: 'Beer name is required.',
|
||||||
|
invalid_type_error: 'Beer name must be a string.',
|
||||||
|
})
|
||||||
|
.min(1, { message: 'Beer name is required.' })
|
||||||
|
.max(100, { message: 'Beer name is too long.' }),
|
||||||
|
description: z
|
||||||
|
.string()
|
||||||
|
.min(1, { message: 'Description is required.' })
|
||||||
|
.max(500, { message: 'Description is too long.' }),
|
||||||
|
abv: z
|
||||||
|
.number({
|
||||||
|
required_error: 'ABV is required.',
|
||||||
|
invalid_type_error: 'ABV must be a number.',
|
||||||
|
})
|
||||||
|
.min(0.1, { message: 'ABV must be greater than 0.1.' })
|
||||||
|
.max(50, { message: 'ABV must be less than 50.' }),
|
||||||
|
ibu: z
|
||||||
|
.number({
|
||||||
|
required_error: 'IBU is required.',
|
||||||
|
invalid_type_error: 'IBU must be a number.',
|
||||||
|
})
|
||||||
|
.min(2, { message: 'IBU must be greater than 2.' })
|
||||||
|
.max(100, { message: 'IBU must be less than 100.' }),
|
||||||
|
typeId: z
|
||||||
|
.string({
|
||||||
|
required_error: 'Type id is required.',
|
||||||
|
invalid_type_error: 'Type id must be a string.',
|
||||||
|
})
|
||||||
|
.uuid({ message: 'Invalid type id.' }),
|
||||||
|
breweryId: z
|
||||||
|
.string({
|
||||||
|
required_error: 'Brewery id is required.',
|
||||||
|
invalid_type_error: 'Brewery id must be a string.',
|
||||||
|
})
|
||||||
|
.uuid({ message: 'Invalid brewery id.' }),
|
||||||
|
});
|
||||||
|
|
||||||
|
export default BeerPostValidationSchema;
|
||||||
Reference in New Issue
Block a user