mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 02:39:03 +00:00
Refactor api requests and components out of pages
This commit is contained in:
@@ -2,5 +2,6 @@
|
||||
"semi": true,
|
||||
"trailingComma": "all",
|
||||
"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 { 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}
|
||||
|
||||
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",
|
||||
"@next/font": "13.1.2",
|
||||
"@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",
|
||||
"eslint": "8.32.0",
|
||||
"eslint-config-next": "13.1.2",
|
||||
"next": "13.1.2",
|
||||
"pino": "^8.8.0",
|
||||
"pino-pretty": "^9.1.1",
|
||||
"react": "18.2.0",
|
||||
"pino": "^8.8.0",
|
||||
"react-dom": "18.2.0",
|
||||
"react-hook-form": "^7.42.1",
|
||||
"react-icons": "^4.7.1",
|
||||
"react": "18.2.0",
|
||||
"typescript": "4.9.4",
|
||||
"zod": "^3.20.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@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",
|
||||
"daisyui": "^2.47.0",
|
||||
"dotenv-cli": "^6.0.0",
|
||||
"eslint": "^8.30.0",
|
||||
"eslint-config-airbnb-base": "15.0.0",
|
||||
"eslint-config-airbnb-typescript": "17.0.0",
|
||||
"eslint-config-next": "^13.0.7",
|
||||
"eslint-config-prettier": "^8.3.0",
|
||||
"eslint-plugin-react": "^7.31.11",
|
||||
"eslint": "8.32.0",
|
||||
"postcss": "^8.4.21",
|
||||
"prettier": "^2.8.1",
|
||||
"prettier-plugin-jsdoc": "^0.4.2",
|
||||
"prettier-plugin-tailwindcss": "^0.2.1",
|
||||
"prettier": "^2.8.1",
|
||||
"prisma": "^4.8.1",
|
||||
"tailwindcss": "^3.2.4",
|
||||
"ts-node": "^10.9.1"
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import BeerPostValidationSchema from '@/validation/BeerPostValidationSchema';
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import { NextApiHandler } from 'next';
|
||||
|
||||
import { z } from 'zod';
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
|
||||
class ServerError extends Error {
|
||||
constructor(message: string, public statusCode: number) {
|
||||
@@ -9,23 +12,10 @@ class ServerError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export const NewBeerInfo = z.object({
|
||||
name: z.string().min(1).max(100),
|
||||
description: z.string().min(1).max(1000),
|
||||
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) => {
|
||||
const handler: NextApiHandler<z.infer<typeof APIResponseValidationSchema>> = async (
|
||||
req,
|
||||
res,
|
||||
) => {
|
||||
try {
|
||||
const { method } = req;
|
||||
|
||||
@@ -33,14 +23,12 @@ const handler: NextApiHandler<z.infer<typeof ResponseBody>> = async (req, res) =
|
||||
throw new ServerError('Method not allowed', 405);
|
||||
}
|
||||
|
||||
const cleanedReqBody = NewBeerInfo.safeParse(req.body);
|
||||
|
||||
const cleanedReqBody = BeerPostValidationSchema.safeParse(req.body);
|
||||
if (!cleanedReqBody.success) {
|
||||
throw new ServerError('Invalid request body', 400);
|
||||
}
|
||||
|
||||
const { name, description, typeId, abv, ibu, breweryId } = cleanedReqBody.data;
|
||||
|
||||
const user = await DBClient.instance.user.findFirstOrThrow();
|
||||
|
||||
const newBeerPost = await DBClient.instance.beerPost.create({
|
||||
@@ -67,9 +55,12 @@ const handler: NextApiHandler<z.infer<typeof ResponseBody>> = async (req, res) =
|
||||
},
|
||||
});
|
||||
|
||||
res
|
||||
.status(200)
|
||||
.json({ message: 'Success', statusCode: 200, payload: newBeerPost, success: true });
|
||||
res.status(201).json({
|
||||
message: 'Beer post created successfully',
|
||||
statusCode: 201,
|
||||
payload: newBeerPost,
|
||||
success: true,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof ServerError) {
|
||||
res.status(error.statusCode).json({
|
||||
|
||||
@@ -1,110 +1,18 @@
|
||||
import { GetServerSideProps, NextPage } from 'next';
|
||||
import BeerPostQueryResult from '@/services/BeerPost/types/BeerPostQueryResult';
|
||||
import getBeerPostById from '@/services/BeerPost/getBeerPostById';
|
||||
import Layout from '@/components/Layout';
|
||||
import Layout from '@/components/ui/Layout';
|
||||
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 {
|
||||
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 }) => {
|
||||
console.log(beerPost.beerComments);
|
||||
return (
|
||||
<Layout>
|
||||
<Head>
|
||||
@@ -113,7 +21,8 @@ const BeerByIdPage: NextPage<BeerPageProps> = ({ beerPost }) => {
|
||||
</Head>
|
||||
<main>
|
||||
{beerPost.beerImages[0] && (
|
||||
<img
|
||||
<Image
|
||||
alt={beerPost.beerImages[0].alt}
|
||||
src={beerPost.beerImages[0].url}
|
||||
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="w-10/12 space-y-3">
|
||||
<BeerInfoHeader beerPost={beerPost} />
|
||||
|
||||
<div className="mt-4 flex space-x-3">
|
||||
<div className="w-[60%] space-y-3">
|
||||
<div className="card h-[22rem] bg-base-300"></div>
|
||||
<div className="card h-[44rem] overflow-y-auto bg-base-300">
|
||||
{/* for each comment make a card */}
|
||||
|
||||
{beerPost.beerComments.map((comment) => (
|
||||
<CommentCard key={comment.id} comment={comment} />
|
||||
))}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import BeerForm from '@/components/BeerForm';
|
||||
import Layout from '@/components/Layout';
|
||||
import Layout from '@/components/ui/Layout';
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import getAllBreweryPosts from '@/services/BreweryPost/getAllBreweryPosts';
|
||||
import BreweryPostQueryResult from '@/services/BreweryPost/types/BreweryPostQueryResult';
|
||||
@@ -16,14 +16,13 @@ interface CreateBeerPageProps {
|
||||
const Create: NextPage<CreateBeerPageProps> = ({ breweries, types }) => {
|
||||
return (
|
||||
<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="flex flex-col items-center space-y-1">
|
||||
<BiBeer className="text-5xl" />
|
||||
<h1 className="text-3xl font-bold">Create a New Beer</h1>
|
||||
</div>
|
||||
|
||||
<BeerForm type="create" breweries={breweries} types={types} />
|
||||
<BeerForm formType="create" breweries={breweries} types={types} />
|
||||
</div>
|
||||
</div>
|
||||
</Layout>
|
||||
@@ -32,8 +31,8 @@ const Create: NextPage<CreateBeerPageProps> = ({ breweries, types }) => {
|
||||
|
||||
export const getServerSideProps = async () => {
|
||||
const breweryPosts = await getAllBreweryPosts();
|
||||
|
||||
const beerTypes = await DBClient.instance.beerType.findMany();
|
||||
|
||||
return {
|
||||
props: {
|
||||
breweries: JSON.parse(JSON.stringify(breweryPosts)),
|
||||
|
||||
@@ -1,75 +1,18 @@
|
||||
import { GetServerSideProps, NextPage } from 'next';
|
||||
import getAllBeerPosts from '@/services/BeerPost/getAllBeerPosts';
|
||||
import BeerPostQueryResult from '@/services/BeerPost/types/BeerPostQueryResult';
|
||||
import Link from 'next/link';
|
||||
|
||||
import { useRouter } from 'next/router';
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import Layout from '@/components/Layout';
|
||||
import { FC } from 'react';
|
||||
import Image from 'next/image';
|
||||
import Layout from '@/components/ui/Layout';
|
||||
import Pagination from '../../components/BeerIndex/Pagination';
|
||||
import BeerCard from '../../components/BeerIndex/BeerCard';
|
||||
|
||||
interface BeerPageProps {
|
||||
initialBeerPosts: BeerPostQueryResult[];
|
||||
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 router = useRouter();
|
||||
const { query } = router;
|
||||
@@ -93,13 +36,10 @@ const BeerPage: NextPage<BeerPageProps> = ({ initialBeerPosts, pageCount }) => {
|
||||
|
||||
export const getServerSideProps: GetServerSideProps<BeerPageProps> = async (context) => {
|
||||
const { query } = context;
|
||||
|
||||
const pageNumber = parseInt(query.page_num as string, 10) || 1;
|
||||
|
||||
const pageSize = 12;
|
||||
const numberOfPosts = await DBClient.instance.beerPost.count();
|
||||
const pageCount = numberOfPosts ? Math.ceil(numberOfPosts / pageSize) : 0;
|
||||
|
||||
const beerPosts = await getAllBeerPosts(pageNumber, pageSize);
|
||||
|
||||
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)
|
||||
beerPostId String
|
||||
url String
|
||||
alt String
|
||||
createdAt DateTime @default(now()) @db.Timestamptz(3)
|
||||
updatedAt DateTime? @updatedAt @db.Timestamptz(3)
|
||||
}
|
||||
@@ -106,4 +107,5 @@ model BreweryImage {
|
||||
url String
|
||||
createdAt DateTime @default(now()) @db.Timestamptz(3)
|
||||
updatedAt DateTime? @updatedAt @db.Timestamptz(3)
|
||||
alt String
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ const createNewBeerImages = async ({
|
||||
prisma.beerImage.create({
|
||||
data: {
|
||||
url: 'https://picsum.photos/900/1600',
|
||||
alt: 'Placeholder beer image.',
|
||||
beerPost: { connect: { id: beerPost.id } },
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -21,6 +21,7 @@ const createNewBreweryImages = async ({
|
||||
prisma.breweryImage.create({
|
||||
data: {
|
||||
url: 'https://picsum.photos/900/1600',
|
||||
alt: 'Placeholder brewery image.',
|
||||
breweryPost: { connect: { id: breweryPost.id } },
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -33,11 +33,11 @@ import createNewUsers from './create/createNewUsers';
|
||||
});
|
||||
const [beerPostComments, breweryPostComments] = await Promise.all([
|
||||
createNewBeerPostComments({
|
||||
numberOfComments: 1000,
|
||||
numberOfComments: 500,
|
||||
joinData: { beerPosts, users },
|
||||
}),
|
||||
createNewBreweryPostComments({
|
||||
numberOfComments: 1000,
|
||||
numberOfComments: 500,
|
||||
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,
|
||||
},
|
||||
},
|
||||
|
||||
beerComments: {
|
||||
select: {
|
||||
id: true,
|
||||
@@ -46,11 +45,11 @@ const getAllBeerPosts = async (pageNum: number, pageSize: number) => {
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
beerImages: {
|
||||
select: {
|
||||
url: true,
|
||||
id: true,
|
||||
alt: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -37,6 +37,7 @@ const getBeerPostById = async (id: string) => {
|
||||
},
|
||||
beerImages: {
|
||||
select: {
|
||||
alt: true,
|
||||
url: true,
|
||||
id: true,
|
||||
},
|
||||
|
||||
@@ -9,6 +9,7 @@ export default interface BeerPostQueryResult {
|
||||
beerImages: {
|
||||
url: string;
|
||||
id: string;
|
||||
alt: string;
|
||||
}[];
|
||||
|
||||
ibu: number;
|
||||
@@ -21,7 +22,6 @@ export default interface BeerPostQueryResult {
|
||||
id: string;
|
||||
username: string;
|
||||
};
|
||||
|
||||
beerComments: {
|
||||
id: 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