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:
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 { BeerType } from '@prisma/client';
|
||||
|
||||
import { FunctionComponent } from 'react';
|
||||
import { SubmitHandler, useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
import Button from './ui/Button';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
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 FormInfo from './ui/forms/FormInfo';
|
||||
import FormLabel from './ui/forms/FormLabel';
|
||||
@@ -15,34 +17,18 @@ import FormSelect from './ui/forms/FormSelect';
|
||||
import FormTextArea from './ui/forms/FormTextArea';
|
||||
import FormTextInput from './ui/forms/FormTextInput';
|
||||
|
||||
type IFormInput = z.infer<typeof NewBeerInfo>;
|
||||
type BeerPostT = z.infer<typeof BeerPostValidationSchema>;
|
||||
|
||||
interface BeerFormProps {
|
||||
type: 'edit' | 'create';
|
||||
formType: 'edit' | 'create';
|
||||
// eslint-disable-next-line react/require-default-props
|
||||
defaultValues?: IFormInput;
|
||||
defaultValues?: BeerPostT;
|
||||
breweries?: BreweryPostQueryResult[];
|
||||
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> = ({
|
||||
type,
|
||||
formType,
|
||||
defaultValues,
|
||||
breweries = [],
|
||||
types = [],
|
||||
@@ -51,7 +37,8 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm<IFormInput>({
|
||||
} = useForm<BeerPostT>({
|
||||
resolver: zodResolver(BeerPostValidationSchema),
|
||||
defaultValues: {
|
||||
name: defaultValues?.name,
|
||||
description: defaultValues?.description,
|
||||
@@ -60,47 +47,19 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
||||
},
|
||||
});
|
||||
|
||||
// const navigate = useNavigate();
|
||||
|
||||
const nameValidationSchema = register('name', {
|
||||
required: 'Beer name is required.',
|
||||
});
|
||||
const breweryValidationSchema = register('breweryId', {
|
||||
required: 'Brewery name is required.',
|
||||
});
|
||||
const abvValidationSchema = register('abv', {
|
||||
required: 'ABV is required.',
|
||||
valueAsNumber: true,
|
||||
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;
|
||||
const onSubmit: SubmitHandler<BeerPostT> = async (data) => {
|
||||
switch (formType) {
|
||||
case 'create': {
|
||||
try {
|
||||
const response = await sendCreateBeerPostRequest(data);
|
||||
Router.push(`/beers/${response.id}`);
|
||||
break;
|
||||
} catch (e) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
case 'edit':
|
||||
break;
|
||||
default:
|
||||
@@ -117,13 +76,13 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
||||
<FormSegment>
|
||||
<FormTextInput
|
||||
placeholder="Lorem Ipsum Lager"
|
||||
formValidationSchema={nameValidationSchema}
|
||||
formValidationSchema={register('name')}
|
||||
error={!!errors.name}
|
||||
type="text"
|
||||
id="name"
|
||||
/>
|
||||
</FormSegment>
|
||||
{type === 'create' && breweries.length && (
|
||||
{formType === 'create' && breweries.length && (
|
||||
<>
|
||||
<FormInfo>
|
||||
<FormLabel htmlFor="breweryId">Brewery</FormLabel>
|
||||
@@ -131,7 +90,7 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
||||
</FormInfo>
|
||||
<FormSegment>
|
||||
<FormSelect
|
||||
formRegister={breweryValidationSchema}
|
||||
formRegister={register('breweryId')}
|
||||
error={!!errors.breweryId}
|
||||
id="breweryId"
|
||||
options={breweries.map((brewery) => ({
|
||||
@@ -153,7 +112,7 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
||||
</FormInfo>
|
||||
<FormTextInput
|
||||
placeholder="12"
|
||||
formValidationSchema={abvValidationSchema}
|
||||
formValidationSchema={register('abv', { valueAsNumber: true })}
|
||||
error={!!errors.abv}
|
||||
type="text"
|
||||
id="abv"
|
||||
@@ -166,7 +125,7 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
||||
</FormInfo>
|
||||
<FormTextInput
|
||||
placeholder="52"
|
||||
formValidationSchema={ibuValidationSchema}
|
||||
formValidationSchema={register('ibu', { valueAsNumber: true })}
|
||||
error={!!errors.ibu}
|
||||
type="text"
|
||||
id="lastName"
|
||||
@@ -182,7 +141,7 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
||||
<FormTextArea
|
||||
placeholder="Ratione cumque quas quia aut impedit ea culpa facere. Ut in sit et quas reiciendis itaque."
|
||||
error={!!errors.description}
|
||||
formValidationSchema={descriptionValidationSchema}
|
||||
formValidationSchema={register('description')}
|
||||
id="description"
|
||||
rows={8}
|
||||
/>
|
||||
@@ -194,7 +153,7 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
||||
</FormInfo>
|
||||
<FormSegment>
|
||||
<FormSelect
|
||||
formRegister={typeIdValidationSchema}
|
||||
formRegister={register('typeId')}
|
||||
error={!!errors.typeId}
|
||||
id="typeId"
|
||||
options={types.map((beerType) => ({
|
||||
@@ -207,7 +166,7 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
||||
</FormSegment>
|
||||
|
||||
<Button type="submit">{`${
|
||||
type === 'edit'
|
||||
formType === 'edit'
|
||||
? `Edit ${defaultValues?.name || 'beer post'}`
|
||||
: 'Create beer post'
|
||||
} `}</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 {
|
||||
children: string;
|
||||
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
|
||||
<button type={type} className="btn-primary btn mt-4 w-full rounded-xl">
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
|
||||
Button.defaultProps = {
|
||||
className: '',
|
||||
};
|
||||
|
||||
export default Button;
|
||||
@@ -3,8 +3,6 @@ import { FunctionComponent } from 'react';
|
||||
// import { faTriangleExclamation } from '@fortawesome/free-solid-svg-icons';
|
||||
|
||||
/**
|
||||
* Component for a styled form error message.
|
||||
*
|
||||
* @example
|
||||
* <FormError>Something went wrong!</FormError>;
|
||||
*/
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
import { FunctionComponent, ReactNode } from 'react';
|
||||
|
||||
/** A container for both the form error and form label. */
|
||||
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 }) => (
|
||||
<div className="flex justify-between">{children}</div>
|
||||
);
|
||||
|
||||
@@ -5,9 +5,13 @@ interface FormLabelProps {
|
||||
children: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* @example
|
||||
* <FormLabel htmlFor="name">Name</FormLabel>;
|
||||
*/
|
||||
const FormLabel: FunctionComponent<FormLabelProps> = ({ htmlFor, children }) => (
|
||||
<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}
|
||||
>
|
||||
{children}
|
||||
|
||||
@@ -10,6 +10,29 @@ interface FormSelectProps {
|
||||
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> = ({
|
||||
options,
|
||||
id,
|
||||
@@ -20,7 +43,7 @@ const FormSelect: FunctionComponent<FormSelectProps> = ({
|
||||
}) => (
|
||||
<select
|
||||
id={id}
|
||||
className={`select select-bordered block w-full rounded-lg ${
|
||||
className={`select-bordered select block w-full rounded-lg ${
|
||||
error ? 'select-error' : ''
|
||||
}`}
|
||||
placeholder={placeholder}
|
||||
|
||||
@@ -7,21 +7,36 @@ interface FormTextAreaProps {
|
||||
error: boolean;
|
||||
id: string;
|
||||
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> = ({
|
||||
placeholder = '',
|
||||
formValidationSchema,
|
||||
error,
|
||||
id,
|
||||
rows,
|
||||
className,
|
||||
}) => (
|
||||
<textarea
|
||||
id={id}
|
||||
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' : ''
|
||||
}`}
|
||||
{...formValidationSchema}
|
||||
@@ -29,9 +44,4 @@ const FormTextArea: FunctionComponent<FormTextAreaProps> = ({
|
||||
/>
|
||||
);
|
||||
|
||||
FormTextArea.defaultProps = {
|
||||
placeholder: '',
|
||||
className: '',
|
||||
};
|
||||
|
||||
export default FormTextArea;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/* eslint-disable react/require-default-props */
|
||||
import { FunctionComponent } from 'react';
|
||||
import { FieldError, UseFormRegisterReturn } from 'react-hook-form';
|
||||
import { UseFormRegisterReturn } from 'react-hook-form';
|
||||
|
||||
interface FormInputProps {
|
||||
placeholder?: string;
|
||||
@@ -12,6 +12,25 @@ interface FormInputProps {
|
||||
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> = ({
|
||||
placeholder = '',
|
||||
formValidationSchema,
|
||||
@@ -23,7 +42,7 @@ const FormTextInput: FunctionComponent<FormInputProps> = ({
|
||||
id={id}
|
||||
type={type}
|
||||
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' : ''
|
||||
}`}
|
||||
{...formValidationSchema}
|
||||
|
||||
Reference in New Issue
Block a user