Restructure codebase to use src directory

This commit is contained in:
Aaron William Po
2023-04-11 23:32:06 -04:00
parent 90f2cc2c0c
commit 08422fe24e
141 changed files with 6 additions and 4 deletions

View File

@@ -0,0 +1,104 @@
import sendCreateBeerCommentRequest from '@/requests/sendCreateBeerCommentRequest';
import BeerCommentValidationSchema from '@/services/BeerComment/schema/CreateBeerCommentValidationSchema';
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import { zodResolver } from '@hookform/resolvers/zod';
import { FunctionComponent, useState, useEffect } from 'react';
import { Rating } from 'react-daisyui';
import { useForm, SubmitHandler } from 'react-hook-form';
import { z } from 'zod';
import useBeerPostComments from '@/hooks/useBeerPostComments';
import Button from '../ui/forms/Button';
import FormError from '../ui/forms/FormError';
import FormInfo from '../ui/forms/FormInfo';
import FormLabel from '../ui/forms/FormLabel';
import FormSegment from '../ui/forms/FormSegment';
import FormTextArea from '../ui/forms/FormTextArea';
interface BeerCommentFormProps {
beerPost: z.infer<typeof beerPostQueryResult>;
mutate: ReturnType<typeof useBeerPostComments>['mutate'];
}
const BeerCommentForm: FunctionComponent<BeerCommentFormProps> = ({
beerPost,
mutate,
}) => {
const { register, handleSubmit, formState, reset, setValue } = useForm<
z.infer<typeof BeerCommentValidationSchema>
>({
defaultValues: {
rating: 0,
},
resolver: zodResolver(BeerCommentValidationSchema),
});
const [rating, setRating] = useState(0);
useEffect(() => {
setRating(0);
reset({ rating: 0, content: '' });
}, [reset]);
const onSubmit: SubmitHandler<z.infer<typeof BeerCommentValidationSchema>> = async (
data,
) => {
setValue('rating', 0);
setRating(0);
await sendCreateBeerCommentRequest({
content: data.content,
rating: data.rating,
beerPostId: beerPost.id,
});
await mutate();
reset();
};
const { errors } = formState;
return (
<form onSubmit={handleSubmit(onSubmit)} className="space-y-5">
<div>
<FormInfo>
<FormLabel htmlFor="content">Leave a comment</FormLabel>
<FormError>{errors.content?.message}</FormError>
</FormInfo>
<FormSegment>
<FormTextArea
id="content"
formValidationSchema={register('content')}
placeholder="Comment"
rows={5}
error={!!errors.content?.message}
disabled={formState.isSubmitting}
/>
</FormSegment>
<FormInfo>
<FormLabel htmlFor="rating">Rating</FormLabel>
<FormError>{errors.rating?.message}</FormError>
</FormInfo>
<Rating
value={rating}
onChange={(value) => {
setRating(value);
setValue('rating', value);
}}
>
<Rating.Item name="rating-1" className="mask mask-star" />
<Rating.Item name="rating-1" className="mask mask-star" />
<Rating.Item name="rating-1" className="mask mask-star" />
<Rating.Item name="rating-1" className="mask mask-star" />
<Rating.Item name="rating-1" className="mask mask-star" />
</Rating>
</div>
<div>
<Button type="submit" isSubmitting={formState.isSubmitting}>
Submit
</Button>
</div>
</form>
);
};
export default BeerCommentForm;

View File

@@ -0,0 +1,100 @@
import Link from 'next/link';
import format from 'date-fns/format';
import { FC, useContext } from 'react';
import UserContext from '@/contexts/userContext';
import { FaRegEdit } from 'react-icons/fa';
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import { z } from 'zod';
import useGetLikeCount from '@/hooks/useGetLikeCount';
import useTimeDistance from '@/hooks/useTimeDistance';
import BeerPostLikeButton from './BeerPostLikeButton';
const BeerInfoHeader: FC<{
beerPost: z.infer<typeof beerPostQueryResult>;
}> = ({ beerPost }) => {
const createdAt = new Date(beerPost.createdAt);
const timeDistance = useTimeDistance(createdAt);
const { user } = useContext(UserContext);
const idMatches = user && beerPost.postedBy.id === user.id;
const isPostOwner = !!(user && idMatches);
const { likeCount, mutate } = useGetLikeCount(beerPost.id);
return (
<main className="card flex flex-col justify-center bg-base-300">
<article className="card-body">
<div className="flex justify-between">
<header>
<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>
</header>
{isPostOwner && (
<div className="tooltip tooltip-left" data-tip={`Edit '${beerPost.name}'`}>
<Link
href={`/beers/${beerPost.id}/edit`}
className="btn-outline btn-sm btn"
>
<FaRegEdit className="text-xl" />
</Link>
</div>
)}
</div>
<h3 className="italic">
{' posted by '}
<Link href={`/users/${beerPost.postedBy.id}`} className="link-hover link">
{`${beerPost.postedBy.username} `}
</Link>
{timeDistance && (
<span
className="tooltip tooltip-right"
data-tip={format(createdAt, 'MM/dd/yyyy')}
>
{`${timeDistance} ago`}
</span>
)}
</h3>
<p>{beerPost.description}</p>
<div className="flex justify-between">
<div className="space-y-1">
<div>
<Link
className="link-hover link text-lg font-bold"
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>
{(!!likeCount || likeCount === 0) && (
<span>
Liked by {likeCount} user{likeCount !== 1 && 's'}
</span>
)}
</div>
</div>
<div className="card-actions items-end">
{user && <BeerPostLikeButton beerPostId={beerPost.id} mutateCount={mutate} />}
</div>
</div>
</article>
</main>
);
};
export default BeerInfoHeader;

View File

@@ -0,0 +1,140 @@
/* eslint-disable no-nested-ternary */
import UserContext from '@/contexts/userContext';
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import { FC, MutableRefObject, useContext, useRef } from 'react';
import { z } from 'zod';
import useBeerPostComments from '@/hooks/useBeerPostComments';
import { useRouter } from 'next/router';
import { useInView } from 'react-intersection-observer';
import { FaArrowUp } from 'react-icons/fa';
import BeerCommentForm from './BeerCommentForm';
import CommentCardBody from './CommentCardBody';
import NoCommentsCard from './NoCommentsCard';
import LoadingComponent from './LoadingComponent';
interface BeerPostCommentsSectionProps {
beerPost: z.infer<typeof beerPostQueryResult>;
}
const BeerPostCommentsSection: FC<BeerPostCommentsSectionProps> = ({ beerPost }) => {
const { user } = useContext(UserContext);
const router = useRouter();
const { id } = beerPost;
const pageNum = parseInt(router.query.comments_page as string, 10) || 1;
const PAGE_SIZE = 4;
const { comments, isLoading, mutate, setSize, size, isLoadingMore, isAtEnd } =
useBeerPostComments({
id,
pageNum,
pageSize: PAGE_SIZE,
});
const { ref: lastCommentRef } = useInView({
/**
* When the last comment comes into view, call setSize from useBeerPostComments to
* load more comments.
*/
onChange: (visible) => {
if (!visible || isAtEnd) return;
setSize(size + 1);
},
});
const sectionRef: MutableRefObject<HTMLDivElement | null> = useRef(null);
return (
<div className="w-full space-y-3">
<div className="card h-96 bg-base-300">
<div className="card-body h-full" ref={sectionRef}>
{user ? (
<BeerCommentForm beerPost={beerPost} mutate={mutate} />
) : (
<div className="flex h-full flex-col items-center justify-center">
<span className="text-lg font-bold">Log in to leave a comment.</span>
</div>
)}
</div>
</div>
{
/**
* If the comments are loading, show a loading component. Otherwise, show the
* comments.
*/
isLoading ? (
<div className="card bg-base-300 pb-6">
<LoadingComponent length={PAGE_SIZE} />
</div>
) : (
<>
{!!comments.length && (
<div className="card bg-base-300 pb-6">
{comments.map((comment, index) => {
const isLastComment = index === comments.length - 1;
/**
* Attach a ref to the last comment in the list. When it comes into
* view, the component will call setSize to load more comments.
*/
return (
<div
ref={isLastComment ? lastCommentRef : undefined}
key={comment.id}
>
<CommentCardBody comment={comment} mutate={mutate} />
</div>
);
})}
{
/**
* If there are more comments to load, show a loading component with a
* skeleton loader and a loading spinner.
*/
!!isLoadingMore && (
<LoadingComponent length={Math.floor(PAGE_SIZE / 2)} />
)
}
{
/**
* If the user has scrolled to the end of the comments, show a button
* that will scroll them back to the top of the comments section.
*/
!!isAtEnd && (
<div className="flex h-20 items-center justify-center text-center">
<div
className="tooltip tooltip-bottom"
data-tip="Scroll back to top of comments."
>
<button
type="button"
className="btn-ghost btn-sm btn"
aria-label="Scroll back to top of comments"
onClick={() => {
sectionRef.current?.scrollIntoView({
behavior: 'smooth',
});
}}
>
<FaArrowUp />
</button>
</div>
</div>
)
}
</div>
)}
{!comments.length && <NoCommentsCard />}
</>
)
}
</div>
);
};
export default BeerPostCommentsSection;

View File

@@ -0,0 +1,57 @@
import useCheckIfUserLikesBeerPost from '@/hooks/useCheckIfUserLikesBeerPost';
import sendLikeRequest from '@/requests/sendLikeRequest';
import { FC, useEffect, useState } from 'react';
import { FaThumbsUp, FaRegThumbsUp } from 'react-icons/fa';
import useGetLikeCount from '@/hooks/useGetLikeCount';
const BeerPostLikeButton: FC<{
beerPostId: string;
mutateCount: ReturnType<typeof useGetLikeCount>['mutate'];
}> = ({ beerPostId, mutateCount }) => {
const { isLiked, mutate: mutateLikeStatus } = useCheckIfUserLikesBeerPost(beerPostId);
const [loading, setLoading] = useState(true);
useEffect(() => {
setLoading(false);
}, [isLiked]);
const handleLike = async () => {
try {
setLoading(true);
await sendLikeRequest(beerPostId);
await mutateCount();
await mutateLikeStatus();
setLoading(false);
} catch (e) {
setLoading(false);
}
};
return (
<button
type="button"
className={`btn gap-2 rounded-2xl ${
!isLiked ? 'btn-ghost outline' : 'btn-primary'
}`}
onClick={() => {
handleLike();
}}
disabled={loading}
>
{isLiked ? (
<>
<FaThumbsUp className="text-2xl" />
Liked
</>
) : (
<>
<FaRegThumbsUp className="text-2xl" />
Like
</>
)}
</button>
);
};
export default BeerPostLikeButton;

View File

@@ -0,0 +1,34 @@
import BeerRecommendationQueryResult from '@/services/BeerPost/schema/BeerRecommendationQueryResult';
import Link from 'next/link';
import { FunctionComponent } from 'react';
interface BeerRecommendationsProps {
beerRecommendations: BeerRecommendationQueryResult[];
}
const BeerRecommendations: FunctionComponent<BeerRecommendationsProps> = ({
beerRecommendations,
}) => {
return (
<div className="card sticky top-2 h-full overflow-y-scroll bg-base-300">
<div className="card-body space-y-3">
{beerRecommendations.map((beerPost) => (
<div key={beerPost.id} className="w-full">
<div>
<Link className="link-hover" href={`/beers/${beerPost.id}`} scroll={false}>
<h2 className="text-2xl font-bold">{beerPost.name}</h2>
</Link>
<Link href={`/breweries/${beerPost.brewery.id}`} className="link-hover">
<p className="text-lg font-semibold">{beerPost.brewery.name}</p>
</Link>
</div>
<p>{beerPost.abv}% ABV</p>
<p>{beerPost.ibu} IBU</p>
</div>
))}
</div>
</div>
);
};
export default BeerRecommendations;

View File

@@ -0,0 +1,105 @@
import UserContext from '@/contexts/userContext';
import useBeerPostComments from '@/hooks/useBeerPostComments';
import useTimeDistance from '@/hooks/useTimeDistance';
import BeerCommentQueryResult from '@/services/BeerComment/schema/BeerCommentQueryResult';
import format from 'date-fns/format';
import Link from 'next/link';
import { FC, useContext } from 'react';
import { Rating } from 'react-daisyui';
import { FaEllipsisH } from 'react-icons/fa';
import { useInView } from 'react-intersection-observer';
import { z } from 'zod';
interface CommentCardProps {
comment: z.infer<typeof BeerCommentQueryResult>;
mutate: ReturnType<typeof useBeerPostComments>['mutate'];
ref?: ReturnType<typeof useInView>['ref'];
}
const CommentCardDropdown: FC<CommentCardProps> = ({ comment, mutate }) => {
const { user } = useContext(UserContext);
const isCommentOwner = user?.id === comment.postedBy.id;
const handleDelete = async () => {
const response = await fetch(`/api/beer-comments/${comment.id}`, {
method: 'DELETE',
});
if (!response.ok) {
throw new Error('Failed to delete comment');
}
await mutate();
};
return (
<div className="dropdown">
<label tabIndex={0} className="btn-ghost btn-sm btn m-1">
<FaEllipsisH />
</label>
<ul
tabIndex={0}
className="dropdown-content menu rounded-box w-52 bg-base-100 p-2 shadow"
>
<li>
{isCommentOwner ? (
<button onClick={handleDelete}>Delete</button>
) : (
<button>Report</button>
)}
</li>
</ul>
</div>
);
};
const CommentCardBody: FC<CommentCardProps> = ({ comment, mutate, ref }) => {
const { user } = useContext(UserContext);
const timeDistance = useTimeDistance(new Date(comment.createdAt));
return (
<div className="card-body animate-in fade-in-10" ref={ref}>
<div className="flex flex-col justify-between sm:flex-row">
<div>
<h3 className="font-semibold sm:text-2xl">
<Link href={`/users/${comment.postedBy.id}`} className="link-hover link">
{comment.postedBy.username}
</Link>
</h3>
<h4 className="italic">
posted{' '}
<time
className="tooltip tooltip-bottom"
data-tip={format(new Date(comment.createdAt), 'MM/dd/yyyy')}
>
{timeDistance}
</time>{' '}
ago
</h4>
</div>
{user && <CommentCardDropdown comment={comment} mutate={mutate} />}
</div>
<div className="space-y-1">
<Rating value={comment.rating}>
{Array.from({ length: 5 }).map((val, index) => (
<Rating.Item
name="rating-1"
className="mask mask-star cursor-default"
disabled
aria-disabled
key={index}
/>
))}
</Rating>
<p>{comment.content}</p>
</div>
</div>
);
};
export default CommentCardBody;

View File

@@ -0,0 +1,19 @@
const CommentLoadingCardBody = () => {
return (
<div className="animate card-body h-52 fade-in-10">
<div className="flex animate-pulse space-x-4 slide-in-from-top">
<div className="flex-1 space-y-4 py-1">
<div className="h-4 w-3/4 rounded bg-base-100" />
<div className="space-y-2">
<div className="h-4 rounded bg-base-100" />
<div className="h-4 w-11/12 rounded bg-base-100" />
<div className="h-4 w-10/12 rounded bg-base-100" />
<div className="h-4 w-11/12 rounded bg-base-100" />
</div>
</div>
</div>
</div>
);
};
export default CommentLoadingCardBody;

View File

@@ -0,0 +1,22 @@
import { FC } from 'react';
import Spinner from '../ui/Spinner';
import CommentLoadingCardBody from './CommentLoadingCardBody';
interface LoadingComponentProps {
length: number;
}
const LoadingComponent: FC<LoadingComponentProps> = ({ length }) => {
return (
<>
{Array.from({ length }).map((_, i) => (
<CommentLoadingCardBody key={i} />
))}
<div className="p-1">
<Spinner size="sm" />
</div>
</>
);
};
export default LoadingComponent;

View File

@@ -0,0 +1,13 @@
const NoCommentsCard = () => {
return (
<div className="card bg-base-300">
<div className="card-body h-64">
<div className="flex h-full flex-col items-center justify-center">
<span className="text-lg font-bold">No comments yet.</span>
</div>
</div>
</div>
);
};
export default NoCommentsCard;

View File

@@ -0,0 +1,33 @@
import Link from 'next/link';
import { FC } from 'react';
import Image from 'next/image';
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import { z } from 'zod';
const BeerCard: FC<{ post: z.infer<typeof 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].path}
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;

View File

@@ -0,0 +1,32 @@
import Link from 'next/link';
import { FaArrowLeft, FaArrowRight } from 'react-icons/fa';
import { FC } from 'react';
interface PaginationProps {
pageNum: number;
pageCount: number;
}
const BeerIndexPaginationBar: FC<PaginationProps> = ({ pageCount, pageNum }) => {
return (
<div className="btn-group">
<Link
className={`btn ${pageNum === 1 ? 'btn-disabled' : ''}`}
href={{ pathname: '/beers', query: { page_num: pageNum - 1 } }}
scroll={false}
>
<FaArrowLeft />
</Link>
<button className="btn">Page {pageNum}</button>
<Link
className={`btn ${pageNum === pageCount ? 'btn-disabled' : ''}`}
href={{ pathname: '/beers', query: { page_num: pageNum + 1 } }}
scroll={false}
>
<FaArrowRight />
</Link>
</div>
);
};
export default BeerIndexPaginationBar;

View File

@@ -0,0 +1,172 @@
import sendCreateBeerPostRequest from '@/requests/sendCreateBeerPostRequest';
import CreateBeerPostValidationSchema from '@/services/BeerPost/schema/CreateBeerPostValidationSchema';
import { zodResolver } from '@hookform/resolvers/zod';
import { BeerType } from '@prisma/client';
import router from 'next/router';
import { FunctionComponent, useState } from 'react';
import { useForm, SubmitHandler } from 'react-hook-form';
import { z } from 'zod';
import BreweryPostQueryResult from '@/services/BreweryPost/types/BreweryPostQueryResult';
import ErrorAlert from './ui/alerts/ErrorAlert';
import Button from './ui/forms/Button';
import FormError from './ui/forms/FormError';
import FormInfo from './ui/forms/FormInfo';
import FormLabel from './ui/forms/FormLabel';
import FormSegment from './ui/forms/FormSegment';
import FormSelect from './ui/forms/FormSelect';
import FormTextArea from './ui/forms/FormTextArea';
import FormTextInput from './ui/forms/FormTextInput';
type CreateBeerPostSchema = z.infer<typeof CreateBeerPostValidationSchema>;
interface BeerFormProps {
breweries: z.infer<typeof BreweryPostQueryResult>[];
types: BeerType[];
}
const CreateBeerPostForm: FunctionComponent<BeerFormProps> = ({
breweries = [],
types = [],
}) => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<CreateBeerPostSchema>({
resolver: zodResolver(CreateBeerPostValidationSchema),
});
const [error, setError] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const onSubmit: SubmitHandler<CreateBeerPostSchema> = async (data) => {
try {
setIsSubmitting(true);
const response = await sendCreateBeerPostRequest(data);
router.push(`/beers/${response.id}`);
} catch (e) {
if (!(e instanceof Error)) {
setError('Something went wrong');
return;
}
setError(e.message);
}
};
return (
<form className="form-control" onSubmit={handleSubmit(onSubmit)}>
<div>{error && <ErrorAlert error={error} setError={setError} />}</div>
<FormInfo>
<FormLabel htmlFor="name">Name</FormLabel>
<FormError>{errors.name?.message}</FormError>
</FormInfo>
<FormSegment>
<FormTextInput
placeholder="Lorem Ipsum Lager"
formValidationSchema={register('name')}
error={!!errors.name}
type="text"
id="name"
disabled={isSubmitting}
/>
</FormSegment>
<div className="flex flex-wrap">
<div className="mb-2 w-full md:mb-0 md:w-1/2 md:pr-3">
<FormInfo>
<FormLabel htmlFor="breweryId">Brewery</FormLabel>
<FormError>{errors.breweryId?.message}</FormError>
</FormInfo>
<FormSegment>
<FormSelect
disabled={isSubmitting}
formRegister={register('breweryId')}
error={!!errors.breweryId}
id="breweryId"
options={breweries.map((brewery) => ({
value: brewery.id,
text: brewery.name,
}))}
placeholder="Brewery"
message="Pick a brewery"
/>
</FormSegment>
</div>
<div className="mb-2 w-full md:mb-0 md:w-1/2 md:pl-3">
<FormInfo>
<FormLabel htmlFor="typeId">Type</FormLabel>
<FormError>{errors.typeId?.message}</FormError>
</FormInfo>
<FormSegment>
<FormSelect
disabled={isSubmitting}
formRegister={register('typeId')}
error={!!errors.typeId}
id="typeId"
options={types.map((beerType) => ({
value: beerType.id,
text: beerType.name,
}))}
placeholder="Beer type"
message="Pick a beer type"
/>
</FormSegment>
</div>
</div>
<div className="flex flex-wrap md:mb-3">
<div className="mb-2 w-full md:mb-0 md:w-1/2 md:pr-3">
<FormInfo>
<FormLabel htmlFor="abv">ABV</FormLabel>
<FormError>{errors.abv?.message}</FormError>
</FormInfo>
<FormTextInput
disabled={isSubmitting}
placeholder="12"
formValidationSchema={register('abv', { valueAsNumber: true })}
error={!!errors.abv}
type="text"
id="abv"
/>
</div>
<div className="mb-2 w-full md:mb-0 md:w-1/2 md:pl-3">
<FormInfo>
<FormLabel htmlFor="ibu">IBU</FormLabel>
<FormError>{errors.ibu?.message}</FormError>
</FormInfo>
<FormTextInput
disabled={isSubmitting}
placeholder="52"
formValidationSchema={register('ibu', { valueAsNumber: true })}
error={!!errors.ibu}
type="text"
id="lastName"
/>
</div>
</div>
<FormInfo>
<FormLabel htmlFor="description">Description</FormLabel>
<FormError>{errors.description?.message}</FormError>
</FormInfo>
<FormSegment>
<FormTextArea
disabled={isSubmitting}
placeholder="Ratione cumque quas quia aut impedit ea culpa facere. Ut in sit et quas reiciendis itaque."
error={!!errors.description}
formValidationSchema={register('description')}
id="description"
rows={8}
/>
</FormSegment>
<div className="mt-6">
<Button type="submit" isSubmitting={isSubmitting}>
{isSubmitting ? 'Submitting...' : 'Submit'}
</Button>
</div>
</form>
);
};
export default CreateBeerPostForm;

View File

@@ -0,0 +1,147 @@
import sendEditBeerPostRequest from '@/requests/sendEditBeerPostRequest';
import EditBeerPostValidationSchema from '@/services/BeerPost/schema/EditBeerPostValidationSchema';
import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter } from 'next/router';
import { FC, useState } from 'react';
import { useForm, SubmitHandler } from 'react-hook-form';
import { z } from 'zod';
import ErrorAlert from './ui/alerts/ErrorAlert';
import Button from './ui/forms/Button';
import FormError from './ui/forms/FormError';
import FormInfo from './ui/forms/FormInfo';
import FormLabel from './ui/forms/FormLabel';
import FormSegment from './ui/forms/FormSegment';
import FormTextArea from './ui/forms/FormTextArea';
import FormTextInput from './ui/forms/FormTextInput';
type EditBeerPostSchema = z.infer<typeof EditBeerPostValidationSchema>;
interface EditBeerPostFormProps {
previousValues: EditBeerPostSchema;
}
const EditBeerPostForm: FC<EditBeerPostFormProps> = ({ previousValues }) => {
const router = useRouter();
const {
register,
handleSubmit,
formState: { errors },
} = useForm<EditBeerPostSchema>({
resolver: zodResolver(EditBeerPostValidationSchema),
defaultValues: previousValues,
});
const [error, setError] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const onSubmit: SubmitHandler<EditBeerPostSchema> = async (data) => {
try {
setIsSubmitting(true);
await sendEditBeerPostRequest(data);
router.push(`/beers/${data.id}`);
} catch (e) {
setIsSubmitting(false);
if (!(e instanceof Error)) {
setError('Something went wrong');
return;
}
setError(e.message);
}
};
const onDelete = async () => {
try {
const response = await fetch(`/api/beers/${previousValues.id}`, {
method: 'DELETE',
});
if (response.status === 200) {
router.push('/beers');
}
} catch (e) {
console.error(e);
}
};
return (
<form className="form-control" onSubmit={handleSubmit(onSubmit)}>
<div className="mb-5">
{error && <ErrorAlert error={error} setError={setError} />}
</div>
<FormInfo>
<FormLabel htmlFor="name">Name</FormLabel>
<FormError>{errors.name?.message}</FormError>
</FormInfo>
<FormSegment>
<FormTextInput
placeholder="Lorem Ipsum Lager"
formValidationSchema={register('name')}
error={!!errors.name}
type="text"
id="name"
disabled={isSubmitting}
/>
</FormSegment>
<div className="flex flex-wrap sm:text-xs md:mb-3">
<div className="mb-2 w-full md:mb-0 md:w-1/2 md:pr-3">
<FormInfo>
<FormLabel htmlFor="abv">ABV</FormLabel>
<FormError>{errors.abv?.message}</FormError>
</FormInfo>
<FormTextInput
disabled={isSubmitting}
placeholder="12"
formValidationSchema={register('abv', { valueAsNumber: true })}
error={!!errors.abv}
type="text"
id="abv"
/>
</div>
<div className="mb-2 w-full md:mb-0 md:w-1/2 md:pl-3">
<FormInfo>
<FormLabel htmlFor="ibu">IBU</FormLabel>
<FormError>{errors.ibu?.message}</FormError>
</FormInfo>
<FormTextInput
disabled={isSubmitting}
placeholder="52"
formValidationSchema={register('ibu', { valueAsNumber: true })}
error={!!errors.ibu}
type="text"
id="lastName"
/>
</div>
</div>
<FormInfo>
<FormLabel htmlFor="description">Description</FormLabel>
<FormError>{errors.description?.message}</FormError>
</FormInfo>
<FormSegment>
<FormTextArea
disabled={isSubmitting}
placeholder="Ratione cumque quas quia aut impedit ea culpa facere. Ut in sit et quas reiciendis itaque."
error={!!errors.description}
formValidationSchema={register('description')}
id="description"
rows={8}
/>
</FormSegment>
<div className="mt-2 space-y-4">
<Button type="submit" isSubmitting={isSubmitting}>
{isSubmitting ? 'Submitting...' : 'Submit'}
</Button>
<button
className={`btn-primary btn w-full rounded-xl ${isSubmitting ? 'loading' : ''}`}
type="button"
onClick={onDelete}
>
Delete
</button>
</div>
</form>
);
};
export default EditBeerPostForm;

View File

@@ -0,0 +1,91 @@
import sendLoginUserRequest from '@/requests/sendLoginUserRequest';
import LoginValidationSchema from '@/services/User/schema/LoginValidationSchema';
import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter } from 'next/router';
import { useContext, useState } from 'react';
import { useForm, SubmitHandler } from 'react-hook-form';
import { z } from 'zod';
import UserContext from '@/contexts/userContext';
import ErrorAlert from '../ui/alerts/ErrorAlert';
import FormError from '../ui/forms/FormError';
import FormInfo from '../ui/forms/FormInfo';
import FormLabel from '../ui/forms/FormLabel';
import FormSegment from '../ui/forms/FormSegment';
import FormTextInput from '../ui/forms/FormTextInput';
import Button from '../ui/forms/Button';
type LoginT = z.infer<typeof LoginValidationSchema>;
const LoginForm = () => {
const router = useRouter();
const { register, handleSubmit, formState, reset } = useForm<LoginT>({
resolver: zodResolver(LoginValidationSchema),
defaultValues: {
username: '',
password: '',
},
});
const { errors } = formState;
const [responseError, setResponseError] = useState<string>('');
const { mutate } = useContext(UserContext);
const onSubmit: SubmitHandler<LoginT> = async (data) => {
try {
await sendLoginUserRequest(data);
await mutate!();
await router.push(`/user/current`);
} catch (error) {
if (error instanceof Error) {
setResponseError(error.message);
reset();
}
}
};
return (
<form className="form-control w-full space-y-5" onSubmit={handleSubmit(onSubmit)}>
<div>
<FormInfo>
<FormLabel htmlFor="username">username</FormLabel>
<FormError>{errors.username?.message}</FormError>
</FormInfo>
<FormSegment>
<FormTextInput
id="username"
type="text"
formValidationSchema={register('username')}
disabled={formState.isSubmitting}
error={!!errors.username}
placeholder="username"
/>
</FormSegment>
<FormInfo>
<FormLabel htmlFor="password">password</FormLabel>
<FormError>{errors.password?.message}</FormError>
</FormInfo>
<FormSegment>
<FormTextInput
disabled={formState.isSubmitting}
id="password"
type="password"
formValidationSchema={register('password')}
error={!!errors.password}
placeholder="password"
/>
</FormSegment>
</div>
{responseError && <ErrorAlert error={responseError} setError={setResponseError} />}
<div className="w-full">
<Button type="submit" isSubmitting={formState.isSubmitting}>
Login
</Button>
</div>
</form>
);
};
export default LoginForm;

View File

@@ -0,0 +1,180 @@
import sendRegisterUserRequest from '@/requests/sendRegisterUserRequest';
import CreateUserValidationSchema from '@/services/User/schema/CreateUserValidationSchema';
import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter } from 'next/router';
import { FC, useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import ErrorAlert from './ui/alerts/ErrorAlert';
import Button from './ui/forms/Button';
import FormError from './ui/forms/FormError';
import FormInfo from './ui/forms/FormInfo';
import FormLabel from './ui/forms/FormLabel';
import FormSegment from './ui/forms/FormSegment';
import FormTextInput from './ui/forms/FormTextInput';
const RegisterUserForm: FC = () => {
const router = useRouter();
const { reset, register, handleSubmit, formState } = useForm<
z.infer<typeof CreateUserValidationSchema>
>({ resolver: zodResolver(CreateUserValidationSchema) });
const { errors } = formState;
const [serverResponseError, setServerResponseError] = useState('');
const onSubmit = async (data: z.infer<typeof CreateUserValidationSchema>) => {
try {
await sendRegisterUserRequest(data);
reset();
router.push('/', undefined, { shallow: true });
} catch (error) {
setServerResponseError(
error instanceof Error
? error.message
: 'Something went wrong. We could not register your account.',
);
}
};
return (
<form
className="form-control w-full space-y-5"
noValidate
onSubmit={handleSubmit(onSubmit)}
>
<div>
{serverResponseError && (
<ErrorAlert error={serverResponseError} setError={setServerResponseError} />
)}
</div>
<div>
<div className="flex flex-row space-x-3">
<div className="w-[50%]">
<FormInfo>
<FormLabel htmlFor="firstName">First name</FormLabel>
<FormError>{errors.firstName?.message}</FormError>
</FormInfo>
<FormSegment>
<FormTextInput
disabled={formState.isSubmitting}
id="firstName"
type="text"
formValidationSchema={register('firstName')}
error={!!errors.firstName}
placeholder="first name"
/>
</FormSegment>
</div>
<div className="w-[50%]">
<FormInfo>
<FormLabel htmlFor="lastName">Last name</FormLabel>
<FormError>{errors.lastName?.message}</FormError>
</FormInfo>
<FormSegment>
<FormTextInput
disabled={formState.isSubmitting}
id="lastName"
type="text"
formValidationSchema={register('lastName')}
error={!!errors.lastName}
placeholder="last name"
/>
</FormSegment>
</div>
</div>
<div className="flex flex-row space-x-3">
<div className="w-[50%]">
<FormInfo>
<FormLabel htmlFor="email">email</FormLabel>
<FormError>{errors.email?.message}</FormError>
</FormInfo>
<FormSegment>
<FormTextInput
disabled={formState.isSubmitting}
id="email"
type="email"
formValidationSchema={register('email')}
error={!!errors.email}
placeholder="email"
/>
</FormSegment>
</div>
<div className="w-[50%]">
<FormInfo>
<FormLabel htmlFor="username">username</FormLabel>
<FormError>{errors.username?.message}</FormError>
</FormInfo>
<FormSegment>
<FormTextInput
disabled={formState.isSubmitting}
id="username"
type="text"
formValidationSchema={register('username')}
error={!!errors.username}
placeholder="username"
/>
</FormSegment>
</div>
</div>
<div className="flex flex-row space-x-3">
<div className="w-[50%]">
<FormInfo>
<FormLabel htmlFor="password">password</FormLabel>
<FormError>{errors.password?.message}</FormError>
</FormInfo>
<FormSegment>
<FormTextInput
disabled={formState.isSubmitting}
id="password"
type="password"
formValidationSchema={register('password')}
error={!!errors.password}
placeholder="password"
/>
</FormSegment>
</div>
<div className="w-[50%]">
<FormInfo>
<FormLabel htmlFor="confirmPassword">confirm password</FormLabel>
<FormError>{errors.confirmPassword?.message}</FormError>
</FormInfo>
<FormSegment>
<FormTextInput
disabled={formState.isSubmitting}
id="confirmPassword"
type="password"
formValidationSchema={register('confirmPassword')}
error={!!errors.confirmPassword}
placeholder="confirm password"
/>
</FormSegment>
</div>
</div>
<FormInfo>
<FormLabel htmlFor="dateOfBirth">Date of birth</FormLabel>
<FormError>{errors.dateOfBirth?.message}</FormError>
</FormInfo>
<FormSegment>
<FormTextInput
id="dateOfBirth"
disabled={formState.isSubmitting}
type="date"
formValidationSchema={register('dateOfBirth')}
error={!!errors.dateOfBirth}
placeholder="date of birth"
/>
</FormSegment>
<div className="mt-6 w-full">
<Button type="submit" isSubmitting={formState.isSubmitting}>
Register User
</Button>
</div>
</div>
</form>
);
};
export default RegisterUserForm;

View File

@@ -0,0 +1,15 @@
import { FC, ReactNode } from 'react';
import Navbar from './Navbar';
const Layout: FC<{ children: ReactNode }> = ({ children }) => {
return (
<div className="flex h-screen flex-col">
<Navbar />
<div className="top-0 h-full flex-1 overflow-x-auto animate-in fade-in">
{children}
</div>
</div>
);
};
export default Layout;

View File

@@ -0,0 +1,106 @@
/* eslint-disable jsx-a11y/no-noninteractive-tabindex */
/* eslint-disable jsx-a11y/label-has-associated-control */
/* eslint-disable jsx-a11y/label-has-for */
import UserContext from '@/contexts/userContext';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { useContext, useEffect, useState } from 'react';
interface Page {
slug: string;
name: string;
}
const Navbar = () => {
const router = useRouter();
const [currentURL, setCurrentURL] = useState('/');
const { user } = useContext(UserContext);
useEffect(() => {
setCurrentURL(router.asPath);
}, [router.asPath]);
const authenticatedPages: readonly Page[] = [
{ slug: '/account', name: 'Account' },
{ slug: '/api/users/logout', name: 'Logout' },
];
const unauthenticatedPages: readonly Page[] = [
{ slug: '/login', name: 'Login' },
{ slug: '/register', name: 'Register' },
];
const otherPages: readonly Page[] = [
{ slug: '/beers', name: 'Beers' },
{ slug: '/breweries', name: 'Breweries' },
];
const pages: readonly Page[] = [
...otherPages,
...(user ? authenticatedPages : unauthenticatedPages),
];
return (
<nav className="navbar sticky top-0 z-50 bg-primary text-primary-content">
<div className="flex-1">
<Link className="btn-ghost btn normal-case" href="/">
<span className="cursor-pointer text-lg font-bold">The Biergarten App</span>
</Link>
</div>
<div className="hidden flex-none lg:block">
<ul className="menu menu-horizontal p-0">
{pages.map((page) => {
return (
<li key={page.slug}>
<Link tabIndex={0} href={page.slug}>
<span
className={`text-lg uppercase ${
currentURL === page.slug ? 'font-extrabold' : 'font-semibold'
} text-primary-content`}
>
{page.name}
</span>
</Link>
</li>
);
})}
</ul>
</div>
<div className="flex-none lg:hidden">
<div className="dropdown dropdown-end">
<label tabIndex={0} className="btn-ghost btn-circle btn">
<span className="w-10 rounded-full">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
className="inline-block h-5 w-5 stroke-white"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M4 6h16M4 12h16M4 18h16"
/>
</svg>
</span>
</label>
<ul
tabIndex={0}
className="dropdown-content menu rounded-box menu-compact mt-3 w-48 bg-base-100 p-2 shadow"
>
{pages.map((page) => (
<li key={page.slug}>
<Link href={page.slug}>
<span className="select-none text-primary-content">{page.name}</span>
</Link>
</li>
))}
</ul>
</div>
</div>
</nav>
);
};
export default Navbar;

View File

@@ -0,0 +1,44 @@
import { FC } from 'react';
interface SpinnerProps {
size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl';
}
const Spinner: FC<SpinnerProps> = ({ size = 'md' }) => {
const spinnerWidths: Record<NonNullable<SpinnerProps['size']>, `w-[${number}px]`> = {
xs: 'w-[45px]',
sm: 'w-[90px]',
md: 'w-[135px]',
lg: 'w-[180px]',
xl: 'w-[225px]',
};
return (
<div
role="alert"
aria-busy="true"
aria-live="polite"
className="flex flex-col items-center justify-center rounded-3xl text-primary"
>
<svg
aria-hidden="true"
className={`${spinnerWidths[size]} animate-spin fill-base-content`}
viewBox="0 0 100 101"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
fill="currentColor"
/>
<path
d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
fill="currentFill"
/>
</svg>
<span className="sr-only">Loading...</span>
</div>
);
};
export default Spinner;

View File

@@ -0,0 +1,32 @@
import { Dispatch, FC, SetStateAction } from 'react';
import { FiAlertTriangle } from 'react-icons/fi';
interface ErrorAlertProps {
error: string;
setError: Dispatch<SetStateAction<string>>;
}
const ErrorAlert: FC<ErrorAlertProps> = ({ error, setError }) => {
return (
<div className="alert alert-error shadow-lg">
<div>
<FiAlertTriangle className="h-6 w-6" />
<span>{error}</span>
</div>
<div className="flex-none">
<button
className="btn-ghost btn-sm btn"
type="button"
onClick={() => {
setError('');
}}
>
OK
</button>
</div>
</div>
);
};
export default ErrorAlert;

View File

@@ -0,0 +1,23 @@
import { FunctionComponent } from 'react';
interface FormButtonProps {
children: string;
type: 'button' | 'submit' | 'reset';
isSubmitting?: boolean;
}
const Button: FunctionComponent<FormButtonProps> = ({
children,
type,
isSubmitting = false,
}) => (
// eslint-disable-next-line react/button-has-type
<button
type={type}
className={`btn-primary btn w-full rounded-xl ${isSubmitting ? 'loading' : ''}`}
>
{children}
</button>
);
export default Button;

View File

@@ -0,0 +1,16 @@
import { FunctionComponent } from 'react';
/**
* @example
* <FormError>Something went wrong!</FormError>;
*/
const FormError: FunctionComponent<{ children: string | undefined }> = ({ children }) =>
children ? (
<div
className="my-1 h-3 text-xs font-semibold italic text-error-content"
role="alert"
>
{children}
</div>
) : null;
export default FormError;

View File

@@ -0,0 +1,18 @@
import { FunctionComponent, ReactNode } from 'react';
interface FormInfoProps {
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>
);
export default FormInfo;

View File

@@ -0,0 +1,21 @@
import { FunctionComponent } from 'react';
interface FormLabelProps {
htmlFor: string;
children: string;
}
/**
* @example
* <FormLabel htmlFor="name">Name</FormLabel>;
*/
const FormLabel: FunctionComponent<FormLabelProps> = ({ htmlFor, children }) => (
<label
className="my-1 block text-sm font-extrabold uppercase tracking-wide sm:text-xs"
htmlFor={htmlFor}
>
{children}
</label>
);
export default FormLabel;

View File

@@ -0,0 +1,39 @@
import { ReactNode, FC } from 'react';
import Link from 'next/link';
import { IconType } from 'react-icons';
import { BiArrowBack } from 'react-icons/bi';
interface FormPageLayoutProps {
children: ReactNode;
headingText: string;
headingIcon: IconType;
backLink: string;
backLinkText: string;
}
const FormPageLayout: FC<FormPageLayoutProps> = ({
children: FormComponent,
headingIcon,
headingText,
backLink,
backLinkText,
}) => {
return (
<div className="align-center my-20 flex h-fit flex-col items-center justify-center">
<div className="w-8/12">
<div className="tooltip tooltip-bottom absolute" data-tip={backLinkText}>
<Link href={backLink} className="btn-ghost btn-sm btn p-0">
<BiArrowBack className="text-xl" />
</Link>
</div>
<div className="flex flex-col items-center space-y-1">
{headingIcon({ className: 'text-4xl' })}{' '}
<h1 className="text-3xl font-bold">{headingText}</h1>
</div>
<div>{FormComponent}</div>
</div>
</div>
);
};
export default FormPageLayout;

View File

@@ -0,0 +1,12 @@
import { FunctionComponent } from 'react';
/** A container for both the form error and form label. */
interface FormInfoProps {
children: Array<JSX.Element> | JSX.Element;
}
const FormSegment: FunctionComponent<FormInfoProps> = ({ children }) => (
<div className="mb-2">{children}</div>
);
export default FormSegment;

View File

@@ -0,0 +1,64 @@
import { FunctionComponent } from 'react';
import { UseFormRegisterReturn } from 'react-hook-form';
interface FormSelectProps {
options: readonly { value: string; text: string }[];
id: string;
formRegister: UseFormRegisterReturn<string>;
error: boolean;
placeholder: string;
message: string;
disabled?: boolean;
}
/**
* @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,
error,
formRegister,
placeholder,
message,
disabled = false,
}) => (
<select
id={id}
className={`select-bordered select block w-full rounded-lg ${
error ? 'select-error' : ''
}`}
placeholder={placeholder}
disabled={disabled}
{...formRegister}
>
<option value="">{message}</option>
{options.map(({ value, text }) => (
<option key={value} value={value}>
{text}
</option>
))}
</select>
);
export default FormSelect;

View File

@@ -0,0 +1,52 @@
import { FunctionComponent } from 'react';
import { UseFormRegisterReturn } from 'react-hook-form';
interface FormTextAreaProps {
placeholder?: string;
formValidationSchema: UseFormRegisterReturn<string>;
error: boolean;
id: string;
rows: number;
disabled?: boolean;
}
/**
* @example
* <FormTextArea
* id="test"
* formValidationSchema={register('test')}
* error={true}
* placeholder="Test"
* rows={5}
* disabled
* />;
*
* @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.
* @param props.disabled Whether or not the textarea is disabled.
*/
const FormTextArea: FunctionComponent<FormTextAreaProps> = ({
placeholder = '',
formValidationSchema,
error,
id,
rows,
disabled = false,
}) => (
<textarea
id={id}
placeholder={placeholder}
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}
rows={rows}
disabled={disabled}
/>
);
export default FormTextArea;

View File

@@ -0,0 +1,57 @@
/* eslint-disable react/require-default-props */
import { FunctionComponent } from 'react';
import { UseFormRegisterReturn } from 'react-hook-form';
interface FormInputProps {
placeholder?: string;
formValidationSchema: UseFormRegisterReturn<string>;
error: boolean;
// eslint-disable-next-line react/require-default-props
type: 'email' | 'password' | 'text' | 'date';
id: string;
height?: string;
disabled?: boolean;
}
/**
* @example
* <FormTextInput
* placeholder="Lorem Ipsum Lager"
* formValidationSchema={register('name')}
* error={!!errors.name}
* type="text"
* id="name"
* disabled
* />;
*
* @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.
* @param param0.disabled Whether or not the input is disabled.
*/
const FormTextInput: FunctionComponent<FormInputProps> = ({
placeholder = '',
formValidationSchema,
error,
type,
id,
disabled = false,
}) => (
<input
id={id}
type={type}
placeholder={placeholder}
className={`input-bordered input w-full rounded-lg transition ease-in-out ${
error ? 'input-error' : ''
}`}
{...formValidationSchema}
disabled={disabled}
/>
);
export default FormTextInput;

35
src/config/auth/cookie.ts Normal file
View File

@@ -0,0 +1,35 @@
import { NextApiResponse } from 'next';
import { serialize, parse } from 'cookie';
import { SessionRequest } from './types';
import { NODE_ENV, SESSION_MAX_AGE, SESSION_TOKEN_NAME } from '../env';
export function setTokenCookie(res: NextApiResponse, token: string) {
const cookie = serialize(SESSION_TOKEN_NAME, token, {
maxAge: SESSION_MAX_AGE,
httpOnly: false,
secure: NODE_ENV === 'production',
path: '/',
sameSite: 'lax',
});
res.setHeader('Set-Cookie', cookie);
}
export function removeTokenCookie(res: NextApiResponse) {
const cookie = serialize(SESSION_TOKEN_NAME, '', { maxAge: -1, path: '/' });
res.setHeader('Set-Cookie', cookie);
}
export function parseCookies(req: SessionRequest) {
// For API Routes we don't need to parse the cookies.
if (req.cookies) return req.cookies;
// For pages we do need to parse the cookies.
const cookie = req.headers?.cookie;
return parse(cookie || '');
}
export function getTokenCookie(req: SessionRequest) {
const cookies = parseCookies(req);
return cookies[SESSION_TOKEN_NAME];
}

View File

@@ -0,0 +1,24 @@
import findUserByUsername from '@/services/User/findUserByUsername';
import Local from 'passport-local';
import ServerError from '../util/ServerError';
import { validatePassword } from './passwordFns';
const localStrat = new Local.Strategy(async (username, password, done) => {
try {
const user = await findUserByUsername(username);
if (!user) {
throw new ServerError('Username or password is incorrect.', 401);
}
const isValidLogin = await validatePassword(user.hash, password);
if (!isValidLogin) {
throw new ServerError('Username or password is incorrect.', 401);
}
done(null, { id: user.id, username: user.username });
} catch (error) {
done(error);
}
});
export default localStrat;

View File

@@ -0,0 +1,6 @@
import argon2 from 'argon2';
export const hashPassword = async (password: string) => argon2.hash(password);
export const validatePassword = async (hash: string, password: string) =>
argon2.verify(hash, password);

View File

@@ -0,0 +1,53 @@
import { NextApiResponse } from 'next';
import Iron from '@hapi/iron';
import {
SessionRequest,
BasicUserInfoSchema,
UserSessionSchema,
} from '@/config/auth/types';
import { z } from 'zod';
import { SESSION_MAX_AGE, SESSION_SECRET } from '@/config/env';
import { setTokenCookie, getTokenCookie } from './cookie';
import ServerError from '../util/ServerError';
export async function setLoginSession(
res: NextApiResponse,
session: z.infer<typeof BasicUserInfoSchema>,
) {
if (!SESSION_SECRET) {
throw new ServerError('Authentication is not configured.', 500);
}
const createdAt = Date.now();
const obj = { ...session, createdAt, maxAge: SESSION_MAX_AGE };
const token = await Iron.seal(obj, SESSION_SECRET, Iron.defaults);
setTokenCookie(res, token);
}
export async function getLoginSession(req: SessionRequest) {
if (!SESSION_SECRET) {
throw new ServerError('Authentication is not configured.', 500);
}
const token = getTokenCookie(req);
if (!token) {
throw new ServerError('You are not logged in.', 401);
}
const session = await Iron.unseal(token, SESSION_SECRET, Iron.defaults);
const parsed = UserSessionSchema.safeParse(session);
if (!parsed.success) {
throw new ServerError('Session is invalid.', 401);
}
const { createdAt, maxAge } = parsed.data;
const expiresAt = createdAt + maxAge * 1000;
if (Date.now() > expiresAt) {
throw new ServerError('Session expired', 401);
}
return parsed.data;
}

26
src/config/auth/types.ts Normal file
View File

@@ -0,0 +1,26 @@
import GetUserSchema from '@/services/User/schema/GetUserSchema';
import { IncomingMessage } from 'http';
import { NextApiRequest } from 'next';
import { z } from 'zod';
export const BasicUserInfoSchema = z.object({
id: z.string().uuid(),
username: z.string(),
});
export const UserSessionSchema = BasicUserInfoSchema.merge(
z.object({
createdAt: z.number(),
maxAge: z.number(),
}),
);
export interface UserExtendedNextApiRequest extends NextApiRequest {
user?: z.infer<typeof GetUserSchema>;
}
export type SessionRequest = IncomingMessage & {
cookies: Partial<{
[key: string]: string;
}>;
};

View File

@@ -0,0 +1,19 @@
/* eslint-disable @typescript-eslint/naming-convention */
import { v2 as cloudinary } from 'cloudinary';
import { CloudinaryStorage } from 'multer-storage-cloudinary';
import { CLOUDINARY_CLOUD_NAME, CLOUDINARY_KEY, CLOUDINARY_SECRET } from '../env';
cloudinary.config({
cloud_name: CLOUDINARY_CLOUD_NAME,
api_key: CLOUDINARY_KEY,
api_secret: CLOUDINARY_SECRET,
});
// @ts-expect-error
const storage = new CloudinaryStorage({ cloudinary, params: { folder: 'BeerApp' } });
/** Configuration object for Cloudinary image upload. */
const cloudinaryConfig = { cloudinary, storage };
export default cloudinaryConfig;

147
src/config/env/index.ts vendored Normal file
View File

@@ -0,0 +1,147 @@
/* eslint-disable prefer-destructuring */
import { z } from 'zod';
import { env } from 'process';
import ServerError from '../util/ServerError';
import 'dotenv/config';
/**
* Environment variables are validated at runtime to ensure that they are present and have
* the correct type. This is done using the zod library.
*/
const envSchema = z.object({
BASE_URL: z.string().url(),
CLOUDINARY_CLOUD_NAME: z.string(),
CLOUDINARY_KEY: z.string(),
CLOUDINARY_SECRET: z.string(),
CONFIRMATION_TOKEN_SECRET: z.string(),
SESSION_SECRET: z.string(),
SESSION_TOKEN_NAME: z.string(),
SESSION_MAX_AGE: z.coerce.number().positive(),
DATABASE_URL: z.string().url(),
NODE_ENV: z.enum(['development', 'production', 'test']),
SPARKPOST_API_KEY: z.string(),
SPARKPOST_SENDER_ADDRESS: z.string().email(),
});
const parsed = envSchema.safeParse(env);
if (!parsed.success) {
throw new ServerError('Invalid environment variables', 500);
}
/**
* Base URL of the application.
*
* @example
* 'https://example.com';
*/
export const BASE_URL = parsed.data.BASE_URL;
/**
* Cloudinary cloud name.
*
* @example
* 'my-cloud';
*
* @see https://cloudinary.com/documentation/cloudinary_references
* @see https://cloudinary.com/console
*/
export const CLOUDINARY_CLOUD_NAME = parsed.data.CLOUDINARY_CLOUD_NAME;
/**
* Cloudinary API key.
*
* @example
* '123456789012345';
*
* @see https://cloudinary.com/documentation/cloudinary_references
* @see https://cloudinary.com/console
*/
export const CLOUDINARY_KEY = parsed.data.CLOUDINARY_KEY;
/**
* Cloudinary API secret.
*
* @example
* 'abcdefghijklmnopqrstuvwxyz123456';
*
* @see https://cloudinary.com/documentation/cloudinary_references
* @see https://cloudinary.com/console
*/
export const CLOUDINARY_SECRET = parsed.data.CLOUDINARY_SECRET;
/**
* Secret key for signing confirmation tokens.
*
* @example
* 'abcdefghijklmnopqrstuvwxyz123456';
*
* @see README.md for instructions on generating a secret key.
*/
export const CONFIRMATION_TOKEN_SECRET = parsed.data.CONFIRMATION_TOKEN_SECRET;
/**
* Secret key for signing session cookies.
*
* @example
* 'abcdefghijklmnopqrstuvwxyz123456';
*
* @see README.md for instructions on generating a secret key.
*/
export const SESSION_SECRET = parsed.data.SESSION_SECRET;
/**
* Name of the session cookie.
*
* @example
* 'my-app-session';
*/
export const SESSION_TOKEN_NAME = parsed.data.SESSION_TOKEN_NAME;
/**
* Maximum age of the session cookie in milliseconds.
*
* @example
* '86400000'; // 24 hours
*/
export const SESSION_MAX_AGE = parsed.data.SESSION_MAX_AGE;
/**
* URL of the CockroachDB database. CockroachDB uses the PostgreSQL wire protocol.
*
* @example
* 'postgres://username:password@localhost/my-database';
*/
export const DATABASE_URL = parsed.data.DATABASE_URL;
/**
* Node environment.
*
* @example
* 'production';
*
* @see https://nodejs.org/api/process.html#process_process_env
*/
export const NODE_ENV = parsed.data.NODE_ENV;
/**
* SparkPost API key.
*
* @example
* 'abcdefghijklmnopqrstuvwxyz123456';
*
* @see https://app.sparkpost.com/account/api-keys
*/
export const SPARKPOST_API_KEY = parsed.data.SPARKPOST_API_KEY;
/**
* Sender email address for SparkPost.
*
* @example
* 'noreply@example.com';
*
* @see https://app.sparkpost.com/domains/list/sending
*/
export const SPARKPOST_SENDER_ADDRESS = parsed.data.SPARKPOST_SENDER_ADDRESS;

23
src/config/jwt/index.ts Normal file
View File

@@ -0,0 +1,23 @@
import { BasicUserInfoSchema } from '@/config/auth/types';
import jwt from 'jsonwebtoken';
import { z } from 'zod';
import { CONFIRMATION_TOKEN_SECRET } from '../env';
type User = z.infer<typeof BasicUserInfoSchema>;
export const generateConfirmationToken = (user: User) => {
const token = jwt.sign(user, CONFIRMATION_TOKEN_SECRET, { expiresIn: '30m' });
return token;
};
export const verifyConfirmationToken = (token: string) => {
const decoded = jwt.verify(token, CONFIRMATION_TOKEN_SECRET);
const parsed = BasicUserInfoSchema.safeParse(decoded);
if (!parsed.success) {
throw new Error('Invalid token');
}
return parsed.data;
};

View File

@@ -0,0 +1,41 @@
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import type { NextApiRequest, NextApiResponse } from 'next';
import type { RequestHandler } from 'next-connect/dist/types/node';
import type { HandlerOptions } from 'next-connect/dist/types/types';
import { z } from 'zod';
import logger from '../pino/logger';
import ServerError from '../util/ServerError';
import { NODE_ENV } from '../env';
type NextConnectOptionsT = HandlerOptions<
RequestHandler<
NextApiRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>
>;
const NextConnectOptions: NextConnectOptionsT = {
onNoMatch(req, res) {
res.status(405).json({
message: 'Method not allowed.',
statusCode: 405,
success: false,
});
},
onError(error, req, res) {
if (NODE_ENV !== 'production') {
logger.error(error);
}
const message = error instanceof Error ? error.message : 'Internal server error.';
const statusCode = error instanceof ServerError ? error.statusCode : 500;
res.status(statusCode).json({
message,
statusCode,
success: false,
});
},
};
export default NextConnectOptions;

View File

@@ -0,0 +1,31 @@
import { UserExtendedNextApiRequest } from '@/config/auth/types';
import ServerError from '@/config/util/ServerError';
import getBeerPostById from '@/services/BeerPost/getBeerPostById';
import { NextApiResponse } from 'next';
import { NextHandler } from 'next-connect';
interface CheckIfBeerPostOwnerRequest extends UserExtendedNextApiRequest {
query: { id: string };
}
const checkIfBeerPostOwner = async <RequestType extends CheckIfBeerPostOwnerRequest>(
req: RequestType,
res: NextApiResponse,
next: NextHandler,
) => {
const { id } = req.query;
const user = req.user!;
const beerPost = await getBeerPostById(id);
if (!beerPost) {
throw new ServerError('Beer post not found', 404);
}
if (beerPost.postedBy.id !== user.id) {
throw new ServerError('You are not authorized to edit this beer post', 403);
}
return next();
};
export default checkIfBeerPostOwner;

View File

@@ -0,0 +1,25 @@
import { NextApiResponse } from 'next';
import { NextHandler } from 'next-connect';
import findUserById from '@/services/User/findUserById';
import ServerError from '@/config/util/ServerError';
import { getLoginSession } from '../../auth/session';
import { UserExtendedNextApiRequest } from '../../auth/types';
/** Get the current user from the session. Adds the user to the request object. */
const getCurrentUser = async (
req: UserExtendedNextApiRequest,
res: NextApiResponse,
next: NextHandler,
) => {
const session = await getLoginSession(req);
const user = await findUserById(session?.id);
if (!user) {
throw new ServerError('User is not logged in.', 401);
}
req.user = user;
return next();
};
export default getCurrentUser;

View File

@@ -0,0 +1,49 @@
import ServerError from '@/config/util/ServerError';
import { NextApiRequest, NextApiResponse } from 'next';
import { NextHandler } from 'next-connect';
import { z } from 'zod';
/**
* Middleware to validate the request body and/or query against a zod schema.
*
* @example
* const handler = nextConnect(NextConnectConfig).post(
* validateRequest({ bodySchema: BeerPostValidationSchema }),
* getCurrentUser,
* createBeerPost,
* );
*
* @param args
* @param args.bodySchema The body schema to validate against.
* @param args.querySchema The query schema to validate against.
* @throws ServerError with status code 400 if the request body or query is invalid.
*/
const validateRequest =
({
bodySchema,
querySchema,
}: {
bodySchema?: z.ZodSchema<any>;
querySchema?: z.ZodSchema<any>;
}) =>
async (req: NextApiRequest, res: NextApiResponse, next: NextHandler) => {
if (bodySchema) {
const parsed = bodySchema.safeParse(JSON.parse(JSON.stringify(req.body)));
if (!parsed.success) {
throw new ServerError('Invalid request body.', 400);
}
req.body = parsed.data;
}
if (querySchema) {
const parsed = querySchema.safeParse(req.query);
if (!parsed.success) {
throw new ServerError('Invalid request query.', 400);
}
req.query = parsed.data;
}
return next();
};
export default validateRequest;

View File

@@ -0,0 +1,5 @@
import pino from 'pino';
const logger = pino();
export default logger;

View File

@@ -0,0 +1,6 @@
import SparkPost from 'sparkpost';
import { SPARKPOST_API_KEY } from '../env';
const client = new SparkPost(SPARKPOST_API_KEY);
export default client;

View File

@@ -0,0 +1,20 @@
import { SPARKPOST_SENDER_ADDRESS } from '../env';
import client from './client';
interface EmailParams {
address: string;
text: string;
html: string;
subject: string;
}
const sendEmail = async ({ address, text, html, subject }: EmailParams) => {
const from = SPARKPOST_SENDER_ADDRESS;
await client.transmissions.send({
content: { from, html, subject, text },
recipients: [{ address }],
});
};
export default sendEmail;

View File

@@ -0,0 +1,8 @@
class ServerError extends Error {
constructor(message: string, public statusCode: number) {
super(message);
this.name = 'ServerError';
}
}
export default ServerError;

View File

@@ -0,0 +1,13 @@
import useUser from '@/hooks/useUser';
import GetUserSchema from '@/services/User/schema/GetUserSchema';
import { createContext } from 'react';
import { z } from 'zod';
const UserContext = createContext<{
user?: z.infer<typeof GetUserSchema>;
error?: unknown;
isLoading: boolean;
mutate?: ReturnType<typeof useUser>['mutate'];
}>({ isLoading: true });
export default UserContext;

46
src/emails/Welcome.tsx Normal file
View File

@@ -0,0 +1,46 @@
import { Container, Heading, Text, Button, Section } from '@react-email/components';
import { Tailwind } from '@react-email/tailwind';
import { FC } from 'react';
interface WelcomeEmail {
subject?: string;
name?: string;
url?: string;
}
const Welcome: FC<WelcomeEmail> = ({ name, url }) => (
<Tailwind>
<Container className="flex h-full w-full flex-col items-center justify-center">
<Section>
<Heading className="text-2xl font-bold">Welcome to The Biergarten App!</Heading>
<Text>
Hi {name}, welcome to The Biergarten App! We are excited to have you as a member
of our community.
</Text>
<Text>
The Biergarten App is a social network for beer lovers. Here you can share your
favorite beers with the community, and discover new ones. You can also create
your own beer list, and share it with your friends.
</Text>
<Text>
To get started, please verify your email address by clicking the button below.
Once you do so, you will be able to create your profile and start sharing your
favorite beers with the community.
</Text>
<Button href={url}>Verify Email</Button>
<Text className="italic">
Please note that this email was automatically generated, and we kindly ask you
not to reply to it.
</Text>
</Section>
</Container>
</Tailwind>
);
export default Welcome;

View File

@@ -0,0 +1,62 @@
import { GetServerSidePropsContext, GetServerSidePropsResult, PreviewData } from 'next';
import { ParsedUrlQuery } from 'querystring';
import { getLoginSession } from '../config/auth/session';
/**
* Represents a type definition for a function that handles server-side rendering with
* extended capabilities.
*
* @template P - A generic type that represents an object with string keys and any values.
* It defaults to an empty object.
* @template Q - A generic type that represents a parsed URL query object. It defaults to
* the ParsedUrlQuery type.
* @template D - A generic type that represents preview data. It defaults to the
* PreviewData type.
* @param context - The context object containing information about the incoming HTTP
* request.
* @param session - An awaited value of the return type of the getLoginSession function.
* @returns - A promise that resolves to the result of the server-side rendering process.
*/
export type ExtendedGetServerSideProps<
P extends { [key: string]: any } = { [key: string]: any },
Q extends ParsedUrlQuery = ParsedUrlQuery,
D extends PreviewData = PreviewData,
> = (
context: GetServerSidePropsContext<Q, D>,
session: Awaited<ReturnType<typeof getLoginSession>>,
) => Promise<GetServerSidePropsResult<P>>;
/**
* A Higher Order Function that adds authentication requirement to a Next.js server-side
* page component.
*
* @param fn An async function that receives the GetServerSidePropsContext and
* authenticated session as arguments and returns a GetServerSidePropsResult with props
* for the wrapped component.
* @returns A promise that resolves to a GetServerSidePropsResult object with props for
* the wrapped component. If authentication is successful, the GetServerSidePropsResult
* will include props generated by the wrapped component's getServerSideProps method. If
* authentication fails, the GetServerSidePropsResult will include a redirect to the
* login page.
*/
const withPageAuthRequired =
<P extends { [key: string]: any } = { [key: string]: any }>(
fn?: ExtendedGetServerSideProps<P>,
) =>
async (context: GetServerSidePropsContext) => {
try {
const { req } = context;
const session = await getLoginSession(req);
if (!fn) {
return { props: {} };
}
return await fn(context, session);
} catch (error) {
return { redirect: { destination: '/login', permanent: false } };
}
};
export default withPageAuthRequired;

View File

@@ -0,0 +1,70 @@
import BeerCommentQueryResult from '@/services/BeerComment/schema/BeerCommentQueryResult';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { z } from 'zod';
import useSWRInfinite from 'swr/infinite';
interface UseBeerPostCommentsProps {
pageNum: number;
id: string;
pageSize: number;
}
/**
* A custom React hook that fetches comments for a specific beer post.
*
* @param props - The props object.
* @param props.pageNum - The page number of the comments to fetch.
* @param props.id - The ID of the beer post to fetch comments for.
* @param props.pageSize - The number of comments to fetch per page.
* @returns An object containing the fetched comments, the total number of comment pages,
* a boolean indicating if the request is currently loading, and a function to mutate
* the data.
*/
const useBeerPostComments = ({ id, pageSize }: UseBeerPostCommentsProps) => {
const fetcher = async (url: string) => {
const response = await fetch(url);
const json = await response.json();
const count = response.headers.get('X-Total-Count');
const parsed = APIResponseValidationSchema.safeParse(json);
if (!parsed.success) {
throw new Error(parsed.error.message);
}
const parsedPayload = z.array(BeerCommentQueryResult).safeParse(parsed.data.payload);
if (!parsedPayload.success) {
throw new Error(parsedPayload.error.message);
}
const pageCount = Math.ceil(parseInt(count as string, 10) / pageSize);
return { comments: parsedPayload.data, pageCount };
};
const { data, error, isLoading, mutate, size, setSize } = useSWRInfinite(
(index) => `/api/beers/${id}/comments?page_num=${index + 1}&page_size=${pageSize}`,
fetcher,
{ parallel: true },
);
const comments = data?.flatMap((d) => d.comments) ?? [];
const pageCount = data?.[0].pageCount ?? 0;
const isLoadingMore =
isLoading || (size > 0 && data && typeof data[size - 1] === 'undefined');
const isAtEnd = !(size < data?.[0].pageCount!);
return {
comments,
isLoading,
error: error as undefined,
mutate,
size,
setSize,
isLoadingMore,
isAtEnd,
pageCount,
};
};
export default useBeerPostComments;

View File

@@ -0,0 +1,37 @@
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import useSWR from 'swr';
import { z } from 'zod';
/**
* A custom React hook that searches for beer posts that match a given query string.
*
* @param query The search query string to match beer posts against.
* @returns An object containing an array of search results matching the query, an error
* object if an error occurred during the search, and a boolean indicating if the
* request is currently loading.
*/
const useBeerPostSearch = (query: string | undefined) => {
const { data, isLoading, error } = useSWR(
`/api/beers/search?search=${query}`,
async (url) => {
if (!query) return [];
const response = await fetch(url);
if (!response.ok) {
throw new Error(response.statusText);
}
const json = await response.json();
const result = z.array(beerPostQueryResult).parse(json);
return result;
},
);
return {
searchResults: data,
searchError: error as Error | undefined,
isLoading,
};
};
export default useBeerPostSearch;

View File

@@ -0,0 +1,56 @@
import UserContext from '@/contexts/userContext';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { useContext } from 'react';
import useSWR from 'swr';
import { z } from 'zod';
/**
* A custom React hook that checks if the current user has liked a beer post by fetching
* data from the server.
*
* @param beerPostId The ID of the beer post to check for likes.
* @returns An object containing a boolean indicating if the user has liked the beer post,
* an error object if an error occurred during the request, and a boolean indicating if
* the request is currently loading.
* @throws When the user is not logged in, the server returns an error status code, or if
* the response data fails to validate against the expected schema.
*/
const useCheckIfUserLikesBeerPost = (beerPostId: string) => {
const { user } = useContext(UserContext);
const { data, error, isLoading, mutate } = useSWR(
`/api/beers/${beerPostId}/like/is-liked`,
async () => {
if (!user) {
throw new Error('User is not logged in.');
}
const response = await fetch(`/api/beers/${beerPostId}/like/is-liked`);
const json = await response.json();
const parsed = APIResponseValidationSchema.safeParse(json);
if (!parsed.success) {
throw new Error('Invalid API response.');
}
const { payload } = parsed.data;
const parsedPayload = z.object({ isLiked: z.boolean() }).safeParse(payload);
if (!parsedPayload.success) {
throw new Error('Invalid API response.');
}
const { isLiked } = parsedPayload.data;
return isLiked;
},
);
return {
isLiked: data,
error: error as unknown,
isLoading,
mutate,
};
};
export default useCheckIfUserLikesBeerPost;

View File

@@ -0,0 +1,48 @@
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { z } from 'zod';
import useSWR from 'swr';
/**
* Custom hook to fetch the like count for a beer post from the server.
*
* @param beerPostId - The ID of the beer post to fetch the like count for.
* @returns An object with the current like count, as well as metadata about the current
* state of the request.
*/
const useGetLikeCount = (beerPostId: string) => {
const { error, mutate, data, isLoading } = useSWR(
`/api/beers/${beerPostId}/like`,
async (url) => {
const response = await fetch(url);
const json = await response.json();
const parsed = APIResponseValidationSchema.safeParse(json);
if (!parsed.success) {
throw new Error('Failed to parse API response');
}
const parsedPayload = z
.object({
likeCount: z.number(),
})
.safeParse(parsed.data.payload);
if (!parsedPayload.success) {
throw new Error('Failed to parse API response payload');
}
return parsedPayload.data.likeCount;
},
);
return {
error: error as unknown,
isLoading,
mutate,
likeCount: data as number | undefined,
};
};
export default useGetLikeCount;

View File

@@ -0,0 +1,19 @@
import { useState, useEffect } from 'react';
const useMediaQuery = (query: string) => {
const [matches, setMatches] = useState(false);
useEffect(() => {
const media = window.matchMedia(query);
if (media.matches !== matches) {
setMatches(media.matches);
}
const listener = () => setMatches(media.matches);
window.addEventListener('resize', listener);
return () => window.removeEventListener('resize', listener);
}, [matches, query]);
return matches;
};
export default useMediaQuery;

View File

@@ -0,0 +1,22 @@
import UserContext from '@/contexts/userContext';
import { useRouter } from 'next/router';
import { useContext } from 'react';
/**
* Custom React hook that redirects the user to the home page if they are logged in. This
* hook is used to prevent logged in users from accessing the login and signup pages. Must
* be used under the UserContext provider.
*
* @returns {void}
*/
const useRedirectWhenLoggedIn = (): void => {
const { user } = useContext(UserContext);
const router = useRouter();
if (!user) {
return;
}
router.push('/');
};
export default useRedirectWhenLoggedIn;

View File

@@ -0,0 +1,20 @@
import formatDistanceStrict from 'date-fns/formatDistanceStrict';
import { useState, useEffect } from 'react';
/**
* Returns the time distance between the provided date and the current time, using the
* `date-fns` `formatDistanceStrict` function. This hook ensures that the same result is
* calculated on both the server and client, preventing hydration errors.
*
* @param createdAt The date to calculate the time distance from.
* @returns The time distance between the provided date and the current time.
*/
const useTimeDistance = (createdAt: Date) => {
const [timeDistance, setTimeDistance] = useState('');
useEffect(() => {
setTimeDistance(formatDistanceStrict(createdAt, new Date()));
}, [createdAt]);
return timeDistance;
};
export default useTimeDistance;

50
src/hooks/useUser.ts Normal file
View File

@@ -0,0 +1,50 @@
import GetUserSchema from '@/services/User/schema/GetUserSchema';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import useSWR from 'swr';
/**
* A custom React hook that fetches the current user's data from the server.
*
* @returns An object containing the current user's data, a boolean indicating if the
* request is currently loading, and an error object if an error occurred during the
* request.
* @throws When the user is not logged in, the server returns an error status code, or if
* the response data fails to validate against the expected schema.
*/
const useUser = () => {
const {
data: user,
error,
isLoading,
mutate,
} = useSWR('/api/users/current', async (url) => {
if (!document.cookie.includes('token')) {
throw new Error('No token cookie found');
}
const response = await fetch(url);
if (!response.ok) {
document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
throw new Error(response.statusText);
}
const json = await response.json();
const parsed = APIResponseValidationSchema.safeParse(json);
if (!parsed.success) {
throw new Error(parsed.error.message);
}
const parsedPayload = GetUserSchema.safeParse(parsed.data.payload);
if (!parsedPayload.success) {
throw new Error(parsedPayload.error.message);
}
return parsedPayload.data;
});
return { user, isLoading, error: error as unknown, mutate };
};
export default useUser;

22
src/pages/404.tsx Normal file
View File

@@ -0,0 +1,22 @@
// create a 404 next js page using tailwind
import Layout from '@/components/ui/Layout';
import { NextPage } from 'next';
import Head from 'next/head';
const NotFound: NextPage = () => {
return (
<Layout>
<Head>
<title>404 Page Not Found</title>
<meta name="description" content="404 Page Not Found" />
</Head>
<div className="flex h-full flex-col items-center justify-center space-y-4">
<h1 className="text-7xl font-bold">Error: 404</h1>
<h2 className="text-xl font-bold">Page Not Found</h2>
</div>
</Layout>
);
};
export default NotFound;

20
src/pages/500.tsx Normal file
View File

@@ -0,0 +1,20 @@
import Layout from '@/components/ui/Layout';
import { NextPage } from 'next';
import Head from 'next/head';
const ServerErrorPage: NextPage = () => {
return (
<Layout>
<Head>
<title>500 Internal Server Error</title>
<meta name="description" content="500 Internal Server Error" />
</Head>
<div className="flex h-full flex-col items-center justify-center space-y-4">
<h1 className="text-7xl font-bold">Error: 500</h1>
<h2 className="text-xl font-bold">Internal Server Error</h2>
</div>
</Layout>
);
};
export default ServerErrorPage;

29
src/pages/_app.tsx Normal file
View File

@@ -0,0 +1,29 @@
import UserContext from '@/contexts/userContext';
import useUser from '@/hooks/useUser';
import '@/styles/globals.css';
import type { AppProps } from 'next/app';
import { Space_Grotesk } from 'next/font/google';
const spaceGrotesk = Space_Grotesk({
subsets: ['latin'],
});
export default function App({ Component, pageProps }: AppProps) {
const { user, isLoading, error, mutate } = useUser();
return (
<>
<style jsx global>
{`
html {
font-family: ${spaceGrotesk.style.fontFamily};
}
`}
</style>
<UserContext.Provider value={{ user, isLoading, error, mutate }}>
<Component {...pageProps} />
</UserContext.Provider>
</>
);
}

13
src/pages/_document.tsx Normal file
View File

@@ -0,0 +1,13 @@
import { Html, Head, Main, NextScript } from 'next/document';
export default function Document() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}

View File

@@ -0,0 +1,16 @@
import Layout from '@/components/ui/Layout';
import { NextPage } from 'next';
interface AccountPageProps {}
const AccountPage: NextPage<AccountPageProps> = () => {
return (
<Layout>
<div>
<h1>Account Page</h1>
</div>
</Layout>
);
};
export default AccountPage;

View File

@@ -0,0 +1,60 @@
import { UserExtendedNextApiRequest } from '@/config/auth/types';
import getCurrentUser from '@/config/nextConnect/middleware/getCurrentUser';
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
import ServerError from '@/config/util/ServerError';
import DBClient from '@/prisma/DBClient';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiResponse } from 'next';
import { createRouter } from 'next-connect';
import { z } from 'zod';
interface DeleteCommentRequest extends UserExtendedNextApiRequest {
query: { id: string };
}
const deleteComment = async (
req: DeleteCommentRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const { id } = req.query;
const user = req.user!;
const comment = await DBClient.instance.beerComment.findUnique({
where: { id },
});
if (!comment) {
throw new ServerError('Comment not found', 404);
}
if (comment.postedById !== user.id) {
throw new ServerError('You are not authorized to delete this comment', 403);
}
await DBClient.instance.beerComment.delete({
where: { id },
});
res.status(200).json({
success: true,
message: 'Comment deleted successfully',
statusCode: 200,
});
};
const router = createRouter<
DeleteCommentRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>();
router.delete(
validateRequest({
querySchema: z.object({ id: z.string().uuid() }),
}),
getCurrentUser,
deleteComment,
);
const handler = router.handler(NextConnectOptions);
export default handler;

View File

@@ -0,0 +1,102 @@
import DBClient from '@/prisma/DBClient';
import getAllBeerComments from '@/services/BeerComment/getAllBeerComments';
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { UserExtendedNextApiRequest } from '@/config/auth/types';
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
import createNewBeerComment from '@/services/BeerComment/createNewBeerComment';
import BeerCommentValidationSchema from '@/services/BeerComment/schema/CreateBeerCommentValidationSchema';
import { createRouter } from 'next-connect';
import { z } from 'zod';
import getCurrentUser from '@/config/nextConnect/middleware/getCurrentUser';
import { NextApiResponse } from 'next';
import BeerCommentQueryResult from '@/services/BeerComment/schema/BeerCommentQueryResult';
interface CreateCommentRequest extends UserExtendedNextApiRequest {
body: z.infer<typeof BeerCommentValidationSchema>;
query: { id: string };
}
interface GetAllCommentsRequest extends UserExtendedNextApiRequest {
query: { id: string; page_size: string; page_num: string };
}
const createComment = async (
req: CreateCommentRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const { content, rating } = req.body;
const beerPostId = req.query.id;
const newBeerComment: z.infer<typeof BeerCommentQueryResult> =
await createNewBeerComment({
content,
rating,
beerPostId,
userId: req.user!.id,
});
res.status(201).json({
message: 'Beer comment created successfully',
statusCode: 201,
payload: newBeerComment,
success: true,
});
};
const getAll = async (
req: GetAllCommentsRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const beerPostId = req.query.id;
// eslint-disable-next-line @typescript-eslint/naming-convention
const { page_size, page_num } = req.query;
const comments = await getAllBeerComments(
{ id: beerPostId },
{ pageSize: parseInt(page_size, 10), pageNum: parseInt(page_num, 10) },
);
const pageCount = await DBClient.instance.beerComment.count({ where: { beerPostId } });
res.setHeader('X-Total-Count', pageCount);
res.status(200).json({
message: 'Beer comments fetched successfully',
statusCode: 200,
payload: comments,
success: true,
});
};
const router = createRouter<
// I don't want to use any, but I can't figure out how to get the types to work
any,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>();
router.post(
validateRequest({
bodySchema: BeerCommentValidationSchema,
querySchema: z.object({ id: z.string().uuid() }),
}),
getCurrentUser,
createComment,
);
router.get(
validateRequest({
querySchema: z.object({
id: z.string().uuid(),
page_size: z.coerce.number().int().positive(),
page_num: z.coerce.number().int().positive(),
}),
}),
getAll,
);
const handler = router.handler(NextConnectOptions);
export default handler;

View File

@@ -0,0 +1,98 @@
import DBClient from '@/prisma/DBClient';
import { BeerImage } from '@prisma/client';
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { UserExtendedNextApiRequest } from '@/config/auth/types';
import { createRouter, expressWrapper } from 'next-connect';
import getCurrentUser from '@/config/nextConnect/middleware/getCurrentUser';
import multer from 'multer';
import cloudinaryConfig from '@/config/cloudinary';
import { NextApiResponse } from 'next';
import { z } from 'zod';
import ServerError from '@/config/util/ServerError';
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
const { storage } = cloudinaryConfig;
const fileFilter: multer.Options['fileFilter'] = (req, file, cb) => {
const { mimetype } = file;
const isImage = mimetype.startsWith('image/');
if (!isImage) {
cb(null, false);
}
cb(null, true);
};
const uploadMiddleware = expressWrapper(
multer({ storage, fileFilter, limits: { files: 3 } }).array('images'),
);
const BeerPostImageValidationSchema = z.object({
caption: z.string(),
alt: z.string(),
});
interface UploadBeerPostImagesRequest extends UserExtendedNextApiRequest {
files?: Express.Multer.File[];
query: { id: string };
body: z.infer<typeof BeerPostImageValidationSchema>;
}
const processImageData = async (
req: UploadBeerPostImagesRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const { files, user, body } = req;
if (!files || !files.length) {
throw new ServerError('No images uploaded', 400);
}
const beerImagePromises: Promise<BeerImage>[] = [];
files.forEach((file) => {
beerImagePromises.push(
DBClient.instance.beerImage.create({
data: {
alt: body.alt,
postedBy: { connect: { id: user!.id } },
beerPost: { connect: { id: req.query.id } },
path: file.path,
caption: body.caption,
},
}),
);
});
const beerImages = await Promise.all(beerImagePromises);
res.status(200).json({
success: true,
message: `Successfully uploaded ${beerImages.length} image${
beerImages.length > 1 ? 's' : ''
}`,
statusCode: 200,
});
};
const router = createRouter<
UploadBeerPostImagesRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>();
router.post(
getCurrentUser,
// @ts-expect-error
uploadMiddleware,
validateRequest({ bodySchema: BeerPostImageValidationSchema }),
processImageData,
);
const handler = router.handler(NextConnectOptions);
export default handler;
export const config = { api: { bodyParser: false } };

View File

@@ -0,0 +1,90 @@
import getCurrentUser from '@/config/nextConnect/middleware/getCurrentUser';
import getBeerPostById from '@/services/BeerPost/getBeerPostById';
import { UserExtendedNextApiRequest } from '@/config/auth/types';
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
import editBeerPostById from '@/services/BeerPost/editBeerPostById';
import EditBeerPostValidationSchema from '@/services/BeerPost/schema/EditBeerPostValidationSchema';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiResponse } from 'next';
import { createRouter, NextHandler } from 'next-connect';
import { z } from 'zod';
import ServerError from '@/config/util/ServerError';
import DBClient from '@/prisma/DBClient';
interface BeerPostRequest extends UserExtendedNextApiRequest {
query: { id: string };
}
interface EditBeerPostRequest extends BeerPostRequest {
body: z.infer<typeof EditBeerPostValidationSchema>;
}
const checkIfBeerPostOwner = async (
req: BeerPostRequest,
res: NextApiResponse,
next: NextHandler,
) => {
const { user, query } = req;
const { id } = query;
const beerPost = await getBeerPostById(id);
if (!beerPost) {
throw new ServerError('Beer post not found', 404);
}
if (beerPost.postedBy.id !== user!.id) {
throw new ServerError('You cannot edit that beer post.', 403);
}
next();
};
const editBeerPost = async (
req: EditBeerPostRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const {
body,
query: { id },
} = req;
await editBeerPostById(id, body);
res.status(200).json({
message: 'Beer post updated successfully',
success: true,
statusCode: 200,
});
};
const deleteBeerPost = async (req: BeerPostRequest, res: NextApiResponse) => {
const {
query: { id },
} = req;
const deleted = await DBClient.instance.beerPost.delete({
where: { id },
});
if (!deleted) {
throw new ServerError('Beer post not found', 404);
}
res.status(200).json({
message: 'Beer post deleted successfully',
success: true,
statusCode: 200,
});
};
const router = createRouter<
EditBeerPostRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>();
router.put(getCurrentUser, checkIfBeerPostOwner, editBeerPost);
router.delete(getCurrentUser, checkIfBeerPostOwner, deleteBeerPost);
const handler = router.handler(NextConnectOptions);
export default handler;

View File

@@ -0,0 +1,83 @@
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import getBeerPostById from '@/services/BeerPost/getBeerPostById';
import { UserExtendedNextApiRequest } from '@/config/auth/types';
import { createRouter } from 'next-connect';
import { z } from 'zod';
import { NextApiRequest, NextApiResponse } from 'next';
import ServerError from '@/config/util/ServerError';
import createBeerPostLike from '@/services/BeerPostLike/createBeerPostLike';
import removeBeerPostLikeById from '@/services/BeerPostLike/removeBeerPostLikeById';
import findBeerPostLikeById from '@/services/BeerPostLike/findBeerPostLikeById';
import getCurrentUser from '@/config/nextConnect/middleware/getCurrentUser';
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
import DBClient from '@/prisma/DBClient';
const sendLikeRequest = async (
req: UserExtendedNextApiRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const user = req.user!;
const id = req.query.id as string;
const beer = await getBeerPostById(id);
if (!beer) {
throw new ServerError('Could not find a beer post with that id', 404);
}
const alreadyLiked = await findBeerPostLikeById(beer.id, user.id);
const jsonResponse = {
success: true as const,
message: '',
statusCode: 200 as const,
};
if (alreadyLiked) {
await removeBeerPostLikeById(alreadyLiked.id);
jsonResponse.message = 'Successfully unliked beer post';
} else {
await createBeerPostLike({ id, user });
jsonResponse.message = 'Successfully liked beer post';
}
res.status(200).json(jsonResponse);
};
const getLikeCount = async (
req: NextApiRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const id = req.query.id as string;
const likes = await DBClient.instance.beerPostLike.count({
where: { beerPostId: id },
});
res.status(200).json({
success: true,
message: 'Successfully retrieved like count.',
statusCode: 200,
payload: { likeCount: likes },
});
};
const router = createRouter<
UserExtendedNextApiRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>();
router.post(
getCurrentUser,
validateRequest({ querySchema: z.object({ id: z.string().uuid() }) }),
sendLikeRequest,
);
router.get(
validateRequest({ querySchema: z.object({ id: z.string().uuid() }) }),
getLikeCount,
);
const handler = router.handler(NextConnectOptions);
export default handler;

View File

@@ -0,0 +1,49 @@
import getCurrentUser from '@/config/nextConnect/middleware/getCurrentUser';
import { UserExtendedNextApiRequest } from '@/config/auth/types';
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
import DBClient from '@/prisma/DBClient';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiResponse } from 'next';
import { createRouter } from 'next-connect';
import { z } from 'zod';
const checkIfLiked = async (
req: UserExtendedNextApiRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const user = req.user!;
const id = req.query.id as string;
const alreadyLiked = await DBClient.instance.beerPostLike.findFirst({
where: {
beerPostId: id,
likedById: user.id,
},
});
res.status(200).json({
success: true,
message: alreadyLiked ? 'Beer post is liked.' : 'Beer post is not liked.',
statusCode: 200,
payload: { isLiked: !!alreadyLiked },
});
};
const router = createRouter<
UserExtendedNextApiRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>();
router.get(
getCurrentUser,
validateRequest({
querySchema: z.object({
id: z.string().uuid(),
}),
}),
checkIfLiked,
);
const handler = router.handler(NextConnectOptions);
export default handler;

View File

@@ -0,0 +1,52 @@
import { UserExtendedNextApiRequest } from '@/config/auth/types';
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
import { createRouter } from 'next-connect';
import createNewBeerPost from '@/services/BeerPost/createNewBeerPost';
import CreateBeerPostValidationSchema from '@/services/BeerPost/schema/CreateBeerPostValidationSchema';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiResponse } from 'next';
import { z } from 'zod';
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
import getCurrentUser from '@/config/nextConnect/middleware/getCurrentUser';
interface CreateBeerPostRequest extends UserExtendedNextApiRequest {
body: z.infer<typeof CreateBeerPostValidationSchema>;
}
const createBeerPost = async (
req: CreateBeerPostRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const { name, description, typeId, abv, ibu, breweryId } = req.body;
const newBeerPost = await createNewBeerPost({
name,
description,
abv,
ibu,
typeId,
breweryId,
userId: req.user!.id,
});
res.status(201).json({
message: 'Beer post created successfully',
statusCode: 201,
payload: newBeerPost,
success: true,
});
};
const router = createRouter<
CreateBeerPostRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>();
router.post(
validateRequest({ bodySchema: CreateBeerPostValidationSchema }),
getCurrentUser,
createBeerPost,
);
const handler = router.handler(NextConnectOptions);
export default handler;

View File

@@ -0,0 +1,58 @@
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiRequest, NextApiResponse } from 'next';
import { createRouter } from 'next-connect';
import { z } from 'zod';
import DBClient from '@/prisma/DBClient';
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
const SearchSchema = z.object({
search: z.string().min(1),
});
interface SearchAPIRequest extends NextApiRequest {
query: z.infer<typeof SearchSchema>;
}
const search = async (req: SearchAPIRequest, res: NextApiResponse) => {
const { search: query } = req.query;
const beers: z.infer<typeof beerPostQueryResult>[] =
await DBClient.instance.beerPost.findMany({
select: {
id: true,
name: true,
ibu: true,
abv: true,
createdAt: true,
description: true,
postedBy: { select: { username: true, id: true } },
brewery: { select: { name: true, id: true } },
type: { select: { name: true, id: true } },
beerImages: { select: { alt: true, path: true, caption: true, id: true } },
},
where: {
OR: [
{ name: { contains: query, mode: 'insensitive' } },
{ description: { contains: query, mode: 'insensitive' } },
{ brewery: { name: { contains: query, mode: 'insensitive' } } },
{ type: { name: { contains: query, mode: 'insensitive' } } },
],
},
});
res.status(200).json(beers);
};
const router = createRouter<
SearchAPIRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>();
router.get(validateRequest({}), search);
const handler = router.handler(NextConnectOptions);
export default handler;

View File

@@ -0,0 +1,56 @@
import { UserExtendedNextApiRequest } from '@/config/auth/types';
import { verifyConfirmationToken } from '@/config/jwt';
import getCurrentUser from '@/config/nextConnect/middleware/getCurrentUser';
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
import ServerError from '@/config/util/ServerError';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiResponse } from 'next';
import { createRouter } from 'next-connect';
import { z } from 'zod';
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
import updateUserToBeConfirmedById from '@/services/User/updateUserToBeConfirmedById';
const ConfirmUserValidationSchema = z.object({ token: z.string() });
interface ConfirmUserRequest extends UserExtendedNextApiRequest {
query: z.infer<typeof ConfirmUserValidationSchema>;
}
const confirmUser = async (req: ConfirmUserRequest, res: NextApiResponse) => {
const { token } = req.query;
const user = req.user!;
const { id } = verifyConfirmationToken(token);
if (user.id !== id) {
throw new ServerError('Could not confirm user.', 401);
}
if (user.isAccountVerified) {
throw new ServerError('User is already verified.', 400);
}
await updateUserToBeConfirmedById(id);
res.status(200).json({
message: 'User confirmed successfully.',
statusCode: 200,
success: true,
});
};
const router = createRouter<
ConfirmUserRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>();
router.get(
getCurrentUser,
validateRequest({ querySchema: ConfirmUserValidationSchema }),
confirmUser,
);
const handler = router.handler(NextConnectOptions);
export default handler;

View File

@@ -0,0 +1,27 @@
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
import { UserExtendedNextApiRequest } from '@/config/auth/types';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiResponse } from 'next';
import getCurrentUser from '@/config/nextConnect/middleware/getCurrentUser';
import { createRouter } from 'next-connect';
import { z } from 'zod';
const sendCurrentUser = async (req: UserExtendedNextApiRequest, res: NextApiResponse) => {
const { user } = req;
res.status(200).json({
message: `Currently logged in as ${user!.username}`,
statusCode: 200,
success: true,
payload: user,
});
};
const router = createRouter<
UserExtendedNextApiRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>();
router.get(getCurrentUser, sendCurrentUser);
const handler = router.handler(NextConnectOptions);
export default handler;

View File

@@ -0,0 +1,51 @@
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
import passport from 'passport';
import { createRouter, expressWrapper } from 'next-connect';
import localStrat from '@/config/auth/localStrat';
import { setLoginSession } from '@/config/auth/session';
import { NextApiResponse } from 'next';
import { z } from 'zod';
import LoginValidationSchema from '@/services/User/schema/LoginValidationSchema';
import { UserExtendedNextApiRequest } from '@/config/auth/types';
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
import GetUserSchema from '@/services/User/schema/GetUserSchema';
const router = createRouter<
UserExtendedNextApiRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>();
router.post(
validateRequest({ bodySchema: LoginValidationSchema }),
expressWrapper(async (req, res, next) => {
passport.initialize();
passport.use(localStrat);
passport.authenticate(
'local',
{ session: false },
(error: unknown, token: z.infer<typeof GetUserSchema>) => {
if (error) {
next(error);
return;
}
req.user = token;
next();
},
)(req, res, next);
}),
async (req, res) => {
const user = req.user!;
await setLoginSession(res, user);
res.status(200).json({
message: 'Login successful.',
payload: user,
statusCode: 200,
success: true,
});
},
);
const handler = router.handler(NextConnectOptions);
export default handler;

View File

@@ -0,0 +1,28 @@
import { getLoginSession } from '@/config/auth/session';
import { removeTokenCookie } from '@/config/auth/cookie';
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiRequest, NextApiResponse } from 'next';
import { createRouter } from 'next-connect';
import { z } from 'zod';
import ServerError from '@/config/util/ServerError';
const router = createRouter<
NextApiRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>();
router.all(async (req, res) => {
const session = await getLoginSession(req);
if (!session) {
throw new ServerError('You are not logged in.', 400);
}
removeTokenCookie(res);
res.redirect('/');
});
const handler = router.handler(NextConnectOptions);
export default handler;

View File

@@ -0,0 +1,65 @@
import { setLoginSession } from '@/config/auth/session';
import { NextApiRequest, NextApiResponse } from 'next';
import { z } from 'zod';
import ServerError from '@/config/util/ServerError';
import { createRouter } from 'next-connect';
import createNewUser from '@/services/User/createNewUser';
import CreateUserValidationSchema from '@/services/User/schema/CreateUserValidationSchema';
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
import findUserByUsername from '@/services/User/findUserByUsername';
import findUserByEmail from '@/services/User/findUserByEmail';
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import sendConfirmationEmail from '@/services/User/sendConfirmationEmail';
interface RegisterUserRequest extends NextApiRequest {
body: z.infer<typeof CreateUserValidationSchema>;
}
const registerUser = async (req: RegisterUserRequest, res: NextApiResponse) => {
const [usernameTaken, emailTaken] = await Promise.all([
findUserByUsername(req.body.username),
findUserByEmail(req.body.email),
]);
if (usernameTaken) {
throw new ServerError(
'Could not register a user with that username as it is already taken.',
409,
);
}
if (emailTaken) {
throw new ServerError(
'Could not register a user with that email as it is already taken.',
409,
);
}
const user = await createNewUser(req.body);
await setLoginSession(res, {
id: user.id,
username: user.username,
});
await sendConfirmationEmail(user);
res.status(200).json({
success: true,
statusCode: 200,
message: 'User registered successfully.',
payload: user,
});
};
const router = createRouter<
RegisterUserRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>();
router.post(validateRequest({ bodySchema: CreateUserValidationSchema }), registerUser);
const handler = router.handler(NextConnectOptions);
export default handler;

View File

@@ -0,0 +1,66 @@
import { NextPage } from 'next';
import Head from 'next/head';
import React from 'react';
import Layout from '@/components/ui/Layout';
import withPageAuthRequired from '@/getServerSideProps/withPageAuthRequired';
import getBeerPostById from '@/services/BeerPost/getBeerPostById';
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import EditBeerPostForm from '@/components/EditBeerPostForm';
import FormPageLayout from '@/components/ui/forms/FormPageLayout';
import { BiBeer } from 'react-icons/bi';
import { z } from 'zod';
interface EditPageProps {
beerPost: z.infer<typeof beerPostQueryResult>;
}
const EditPage: NextPage<EditPageProps> = ({ beerPost }) => {
const pageTitle = `Edit "${beerPost.name}"`;
return (
<Layout>
<Head>
<title>{pageTitle}</title>
<meta name="description" content={pageTitle} />
</Head>
<FormPageLayout
headingText={pageTitle}
headingIcon={BiBeer}
backLink={`/beers/${beerPost.id}`}
backLinkText={`Back to "${beerPost.name}"`}
>
<EditBeerPostForm
previousValues={{
name: beerPost.name,
abv: beerPost.abv,
ibu: beerPost.ibu,
description: beerPost.description,
id: beerPost.id,
}}
/>
</FormPageLayout>
</Layout>
);
};
export default EditPage;
export const getServerSideProps = withPageAuthRequired<EditPageProps>(
async (context, session) => {
const beerPostId = context.params?.id as string;
const beerPost = await getBeerPostById(beerPostId);
const { id: userId } = session;
if (!beerPost) {
return { notFound: true };
}
const isBeerPostOwner = beerPost.postedBy.id === userId;
return isBeerPostOwner
? { props: { beerPost: JSON.parse(JSON.stringify(beerPost)) } }
: { redirect: { destination: `/beers/${beerPostId}`, permanent: false } };
},
);

View File

@@ -0,0 +1,122 @@
import { NextPage, GetServerSideProps } from 'next';
import Head from 'next/head';
import Image from 'next/image';
import BeerInfoHeader from '@/components/BeerById/BeerInfoHeader';
import BeerPostCommentsSection from '@/components/BeerById/BeerPostCommentsSection';
import BeerRecommendations from '@/components/BeerById/BeerRecommendations';
import Layout from '@/components/ui/Layout';
import getBeerPostById from '@/services/BeerPost/getBeerPostById';
import getBeerRecommendations from '@/services/BeerPost/getBeerRecommendations';
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import { BeerPost } from '@prisma/client';
import { z } from 'zod';
import 'react-responsive-carousel/lib/styles/carousel.min.css'; // requires a loader
import { Carousel } from 'react-responsive-carousel';
import useMediaQuery from '@/hooks/useMediaQuery';
import { Tab } from '@headlessui/react';
interface BeerPageProps {
beerPost: z.infer<typeof beerPostQueryResult>;
beerRecommendations: (BeerPost & {
brewery: { id: string; name: string };
beerImages: { id: string; alt: string; url: string }[];
})[];
}
const BeerByIdPage: NextPage<BeerPageProps> = ({ beerPost, beerRecommendations }) => {
const isMd = useMediaQuery('(min-width: 768px)');
return (
<>
<Head>
<title>{beerPost.name}</title>
<meta name="description" content={beerPost.description} />
</Head>
<Layout>
<div>
<Carousel
className="w-full"
useKeyboardArrows
autoPlay
interval={10000}
infiniteLoop
showThumbs={false}
>
{beerPost.beerImages.map((image, index) => (
<div key={image.id} id={`image-${index}}`} className="w-full">
<Image
alt={image.alt}
src={image.path}
height={1080}
width={1920}
className="h-[42rem] w-full object-cover"
/>
</div>
))}
</Carousel>
<div className="mb-12 mt-10 flex w-full items-center justify-center ">
<div className="w-11/12 space-y-3 xl:w-9/12">
<BeerInfoHeader beerPost={beerPost} />
{isMd ? (
<div className="mt-4 flex flex-row space-x-3 space-y-0">
<div className="w-[60%]">
<BeerPostCommentsSection beerPost={beerPost} />
</div>
<div className="w-[40%]">
<BeerRecommendations beerRecommendations={beerRecommendations} />
</div>
</div>
) : (
<Tab.Group>
<Tab.List className="card flex flex-row bg-base-300">
<Tab className="ui-selected:bg-gray w-1/2 p-3 uppercase">
Comments
</Tab>
<Tab className="ui-selected:bg-gray w-1/2 p-3 uppercase">
Recommendations
</Tab>
</Tab.List>
<Tab.Panels className="mt-2">
<Tab.Panel>
<BeerPostCommentsSection beerPost={beerPost} />
</Tab.Panel>
<Tab.Panel>
<BeerRecommendations beerRecommendations={beerRecommendations} />
</Tab.Panel>
</Tab.Panels>
</Tab.Group>
)}
</div>
</div>
</div>
</Layout>
</>
);
};
export const getServerSideProps: GetServerSideProps<BeerPageProps> = async (context) => {
const beerPost = await getBeerPostById(context.params!.id! as string);
if (!beerPost) {
return { notFound: true };
}
const { type, brewery, id } = beerPost;
const beerRecommendations = await getBeerRecommendations({ type, brewery, id });
const props = {
beerPost: JSON.parse(JSON.stringify(beerPost)),
beerRecommendations: JSON.parse(JSON.stringify(beerRecommendations)),
};
return { props };
};
export default BeerByIdPage;

View File

@@ -0,0 +1,45 @@
import CreateBeerPostForm from '@/components/CreateBeerPostForm';
import FormPageLayout from '@/components/ui/forms/FormPageLayout';
import Layout from '@/components/ui/Layout';
import withPageAuthRequired from '@/getServerSideProps/withPageAuthRequired';
import DBClient from '@/prisma/DBClient';
import getAllBreweryPosts from '@/services/BreweryPost/getAllBreweryPosts';
import BreweryPostQueryResult from '@/services/BreweryPost/types/BreweryPostQueryResult';
import { BeerType } from '@prisma/client';
import { NextPage } from 'next';
import { BiBeer } from 'react-icons/bi';
import { z } from 'zod';
interface CreateBeerPageProps {
breweries: z.infer<typeof BreweryPostQueryResult>[];
types: BeerType[];
}
const Create: NextPage<CreateBeerPageProps> = ({ breweries, types }) => {
return (
<Layout>
<FormPageLayout
headingText="Create a new beer"
headingIcon={BiBeer}
backLink="/beers"
backLinkText="Back to beers"
>
<CreateBeerPostForm breweries={breweries} types={types} />
</FormPageLayout>
</Layout>
);
};
export const getServerSideProps = withPageAuthRequired<CreateBeerPageProps>(async () => {
const breweryPosts = await getAllBreweryPosts();
const beerTypes = await DBClient.instance.beerType.findMany();
return {
props: {
breweries: JSON.parse(JSON.stringify(breweryPosts)),
types: JSON.parse(JSON.stringify(beerTypes)),
},
};
});
export default Create;

78
src/pages/beers/index.tsx Normal file
View File

@@ -0,0 +1,78 @@
import { GetServerSideProps, NextPage } from 'next';
import getAllBeerPosts from '@/services/BeerPost/getAllBeerPosts';
import { useRouter } from 'next/router';
import DBClient from '@/prisma/DBClient';
import Layout from '@/components/ui/Layout';
import BeerIndexPaginationBar from '@/components/BeerIndex/BeerIndexPaginationBar';
import BeerCard from '@/components/BeerIndex/BeerCard';
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import Head from 'next/head';
import { z } from 'zod';
import Link from 'next/link';
import UserContext from '@/contexts/userContext';
import { useContext } from 'react';
interface BeerPageProps {
initialBeerPosts: z.infer<typeof beerPostQueryResult>[];
pageCount: number;
}
const BeerPage: NextPage<BeerPageProps> = ({ initialBeerPosts, pageCount }) => {
const router = useRouter();
const { query } = router;
const { user } = useContext(UserContext);
const pageNum = parseInt(query.page_num as string, 10) || 1;
return (
<Layout>
<Head>
<title>Beer</title>
<meta name="description" content="Beer posts" />
</Head>
<div className="flex items-center justify-center bg-base-100">
<div className="my-10 flex w-10/12 flex-col space-y-4">
<header className="my-10 flex justify-between">
<div className="space-y-2">
<h1 className="text-6xl font-bold">The Biergarten Index</h1>
<h2 className="text-2xl font-bold">
Page {pageNum} of {pageCount}
</h2>
</div>
{!!user && (
<div>
<Link href="/beers/create" className="btn-primary btn">
Create a new beer post
</Link>
</div>
)}
</header>
<div className="grid gap-5 md:grid-cols-2 xl:grid-cols-3">
{initialBeerPosts.map((post) => {
return <BeerCard post={post} key={post.id} />;
})}
</div>
<div className="flex justify-center">
<BeerIndexPaginationBar pageNum={pageNum} pageCount={pageCount} />
</div>
</div>
</div>
</Layout>
);
};
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 {
props: { initialBeerPosts: JSON.parse(JSON.stringify(beerPosts)), pageCount },
};
};
export default BeerPage;

View File

@@ -0,0 +1,79 @@
import Layout from '@/components/ui/Layout';
import { NextPage } from 'next';
import { useRouter } from 'next/router';
import BeerCard from '@/components/BeerIndex/BeerCard';
import { ChangeEvent, useEffect, useState } from 'react';
import Spinner from '@/components/ui/Spinner';
import debounce from 'lodash/debounce';
import useBeerPostSearch from '@/hooks/useBeerPostSearch';
import FormLabel from '@/components/ui/forms/FormLabel';
const DEBOUNCE_DELAY = 300;
const SearchPage: NextPage = () => {
const router = useRouter();
const querySearch = (router.query.search as string) || '';
const [searchValue, setSearchValue] = useState(querySearch);
const { searchResults, isLoading, searchError } = useBeerPostSearch(searchValue);
const debounceSearch = debounce((value: string) => {
router.push({
pathname: '/beers/search',
query: { search: value },
});
}, DEBOUNCE_DELAY);
const onChange = (event: ChangeEvent<HTMLInputElement>) => {
const { value } = event.target;
setSearchValue(value);
debounceSearch(value);
};
useEffect(() => {
debounce(() => {
if (!querySearch || searchValue) {
return;
}
setSearchValue(querySearch);
}, DEBOUNCE_DELAY)();
}, [querySearch, searchValue]);
const showSearchResults = !isLoading && searchResults && !searchError;
return (
<Layout>
<div className="flex h-full w-full flex-col items-center justify-center">
<div className="h-full w-full space-y-20">
<div className="flex h-[50%] w-full items-center justify-center bg-base-200">
<div className="w-8/12">
<FormLabel htmlFor="search">What are you looking for?</FormLabel>
<input
type="text"
id="search"
className="input-bordered input w-full rounded-lg"
onChange={onChange}
value={searchValue}
/>
</div>
</div>
<div className="flex flex-col items-center justify-center">
{!showSearchResults ? (
<Spinner size="lg" />
) : (
<div className="grid w-8/12 gap-4 md:grid-cols-2 lg:grid-cols-3">
{searchResults.map((result) => {
return <BeerCard key={result.id} post={result} />;
})}
</div>
)}
</div>
</div>
</div>
</Layout>
);
};
export default SearchPage;

View File

@@ -0,0 +1,29 @@
import Layout from '@/components/ui/Layout';
import getBreweryPostById from '@/services/BreweryPost/getBreweryPostById';
import BreweryPostQueryResult from '@/services/BreweryPost/types/BreweryPostQueryResult';
import { GetServerSideProps, NextPage } from 'next';
import { z } from 'zod';
interface BreweryPageProps {
breweryPost: z.infer<typeof BreweryPostQueryResult>;
}
const BreweryByIdPage: NextPage<BreweryPageProps> = ({ breweryPost }) => {
return (
<Layout>
<h1 className="text-3xl font-bold underline">{breweryPost.name}</h1>
</Layout>
);
};
export const getServerSideProps: GetServerSideProps<BreweryPageProps> = async (
context,
) => {
const breweryPost = await getBreweryPostById(context.params!.id! as string);
return !breweryPost
? { notFound: true }
: { props: { breweryPost: JSON.parse(JSON.stringify(breweryPost)) } };
};
export default BreweryByIdPage;

View File

@@ -0,0 +1,70 @@
import { GetServerSideProps, NextPage } from 'next';
import Link from 'next/link';
import getAllBreweryPosts from '@/services/BreweryPost/getAllBreweryPosts';
import BreweryPostQueryResult from '@/services/BreweryPost/types/BreweryPostQueryResult';
import Layout from '@/components/ui/Layout';
import { FC } from 'react';
import Image from 'next/image';
import { z } from 'zod';
interface BreweryPageProps {
breweryPosts: z.infer<typeof BreweryPostQueryResult>[];
}
const BreweryCard: FC<{ brewery: z.infer<typeof BreweryPostQueryResult> }> = ({
brewery,
}) => {
return (
<div className="card bg-base-300" key={brewery.id}>
<figure className="card-image h-96">
{brewery.breweryImages.length > 0 && (
<Image
src={brewery.breweryImages[0].path}
alt={brewery.name}
width="1029"
height="110"
/>
)}
</figure>
<div className="card-body space-y-3">
<div>
<h2 className="text-3xl font-bold">
<Link href={`/breweries/${brewery.id}`}>{brewery.name}</Link>
</h2>
<h3 className="text-xl font-semibold">{brewery.location}</h3>
</div>
</div>
</div>
);
};
const BreweryPage: NextPage<BreweryPageProps> = ({ breweryPosts }) => {
return (
<Layout>
<div className="flex items-center justify-center bg-base-100">
<div className="my-10 flex w-10/12 flex-col space-y-4">
<header className="my-10">
<div className="space-y-2">
<h1 className="text-6xl font-bold">Breweries</h1>
</div>
</header>
<div className="grid gap-5 md:grid-cols-1 xl:grid-cols-2">
{breweryPosts.map((brewery) => {
return <BreweryCard brewery={brewery} key={brewery.id} />;
})}
</div>
</div>
</div>
</Layout>
);
};
export const getServerSideProps: GetServerSideProps<BreweryPageProps> = async () => {
const breweryPosts = await getAllBreweryPosts();
return {
props: { breweryPosts: JSON.parse(JSON.stringify(breweryPosts)) },
};
};
export default BreweryPage;

12
src/pages/index.tsx Normal file
View File

@@ -0,0 +1,12 @@
import Layout from '@/components/ui/Layout';
import { NextPage } from 'next';
const Home: NextPage = () => {
return (
<Layout>
<div></div>
</Layout>
);
};
export default Home;

56
src/pages/login/index.tsx Normal file
View File

@@ -0,0 +1,56 @@
import { NextPage } from 'next';
import Layout from '@/components/ui/Layout';
import LoginForm from '@/components/Login/LoginForm';
import Image from 'next/image';
import { FaUserCircle } from 'react-icons/fa';
import Head from 'next/head';
import Link from 'next/link';
import useRedirectWhenLoggedIn from '@/hooks/useRedirectIfLoggedIn';
const LoginPage: NextPage = () => {
useRedirectWhenLoggedIn();
return (
<Layout>
<Head>
<title>Login</title>
<meta name="description" content="Login to your account" />
</Head>
<div className="flex h-full flex-row">
<div className="hidden h-full flex-col items-center justify-center bg-base-100 lg:flex lg:w-[55%]">
<Image
src="https://picsum.photos/5000/5000"
alt="Login Image"
width={4920}
height={4080}
className="h-full w-full object-cover"
/>
</div>
<div className="flex h-full w-full flex-col items-center justify-center bg-base-300 lg:w-[45%]">
<div className="w-10/12 space-y-5 sm:w-9/12">
<div className=" flex flex-col items-center space-y-2">
<FaUserCircle className="text-3xl" />
<h1 className="text-4xl font-bold">Login</h1>
</div>
<LoginForm />
<div className="mt-3 flex flex-col items-center space-y-1">
<Link href="/register" className="text-primary-500 link-hover link italic">
Don&apos;t have an account?
</Link>
<Link
href="/reset-password"
className="text-primary-500 link-hover link italic"
>
Forgot password?
</Link>
</div>
</div>
</div>
</div>
</Layout>
);
};
export default LoginPage;

View File

@@ -0,0 +1,31 @@
import RegisterUserForm from '@/components/RegisterUserForm';
import FormPageLayout from '@/components/ui/forms/FormPageLayout';
import Layout from '@/components/ui/Layout';
import useRedirectWhenLoggedIn from '@/hooks/useRedirectIfLoggedIn';
import { NextPage } from 'next';
import Head from 'next/head';
import { BiUser } from 'react-icons/bi';
const RegisterUserPage: NextPage = () => {
useRedirectWhenLoggedIn();
return (
<Layout>
<Head>
<title>Register User</title>
<meta name="description" content="Register a new user" />
</Head>
<FormPageLayout
headingText="Register User"
headingIcon={BiUser}
backLink="/"
backLinkText="Back to home"
>
<RegisterUserForm />
</FormPageLayout>
</Layout>
);
};
export default RegisterUserPage;

View File

@@ -0,0 +1,40 @@
import Layout from '@/components/ui/Layout';
import Spinner from '@/components/ui/Spinner';
import withPageAuthRequired from '@/getServerSideProps/withPageAuthRequired';
import UserContext from '@/contexts/userContext';
import { GetServerSideProps, NextPage } from 'next';
import { useContext } from 'react';
const ProtectedPage: NextPage = () => {
const { user, isLoading } = useContext(UserContext);
const currentTime = new Date().getHours();
const isMorning = currentTime > 4 && currentTime < 12;
const isAfternoon = currentTime > 12 && currentTime < 18;
const isEvening = (currentTime > 18 && currentTime < 24) || currentTime < 4;
return (
<Layout>
<div className="flex h-full flex-col items-center justify-center space-y-3">
{isLoading && <Spinner size="xl" />}
{user && (
<>
<h1 className="text-7xl font-bold">
Good {isMorning && 'morning'}
{isAfternoon && 'afternoon'}
{isEvening && 'evening'}
{`, ${user?.firstName}!`}
</h1>
<h2 className="text-4xl font-bold">Welcome to the Biergarten App!</h2>
</>
)}
</div>
</Layout>
);
};
export const getServerSideProps: GetServerSideProps = withPageAuthRequired();
export default ProtectedPage;

18
src/prisma/DBClient.ts Normal file
View File

@@ -0,0 +1,18 @@
import { PrismaClient } from '@prisma/client';
import { NODE_ENV } from '@/config/env';
const globalForPrisma = global as unknown as { prisma: PrismaClient };
const DBClient = {
instance:
globalForPrisma.prisma ||
new PrismaClient({
log: ['info', 'warn'],
}),
};
if (NODE_ENV !== 'production') {
globalForPrisma.prisma = DBClient.instance;
}
export default DBClient;

1
src/prisma/ERD.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 104 KiB

View File

@@ -0,0 +1,171 @@
-- CreateTable
CREATE TABLE "User" (
"id" STRING NOT NULL,
"username" STRING NOT NULL,
"firstName" STRING NOT NULL,
"lastName" STRING NOT NULL,
"hash" STRING NOT NULL,
"email" STRING NOT NULL,
"createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMPTZ(3),
"isAccountVerified" BOOL NOT NULL DEFAULT false,
"dateOfBirth" TIMESTAMP(3) NOT NULL,
CONSTRAINT "User_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "BeerPost" (
"id" STRING NOT NULL,
"name" STRING NOT NULL,
"ibu" FLOAT8 NOT NULL,
"abv" FLOAT8 NOT NULL,
"description" STRING NOT NULL,
"postedById" STRING NOT NULL,
"breweryId" STRING NOT NULL,
"typeId" STRING NOT NULL,
"createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMPTZ(3),
CONSTRAINT "BeerPost_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "BeerPostLike" (
"id" STRING NOT NULL,
"beerPostId" STRING NOT NULL,
"likedById" STRING NOT NULL,
"createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMPTZ(3),
CONSTRAINT "BeerPostLike_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "BeerComment" (
"id" STRING NOT NULL,
"rating" INT4 NOT NULL,
"beerPostId" STRING NOT NULL,
"postedById" STRING NOT NULL,
"content" STRING NOT NULL,
"createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMPTZ(3),
CONSTRAINT "BeerComment_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "BeerType" (
"id" STRING NOT NULL,
"name" STRING NOT NULL,
"createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMPTZ(3),
"postedById" STRING NOT NULL,
CONSTRAINT "BeerType_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "BreweryPost" (
"id" STRING NOT NULL,
"name" STRING NOT NULL,
"location" STRING NOT NULL,
"description" STRING NOT NULL,
"createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMPTZ(3),
"postedById" STRING NOT NULL,
CONSTRAINT "BreweryPost_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "BreweryComment" (
"id" STRING NOT NULL,
"rating" INT4 NOT NULL,
"breweryPostId" STRING NOT NULL,
"postedById" STRING NOT NULL,
"content" STRING NOT NULL,
"createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMPTZ(3),
CONSTRAINT "BreweryComment_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "BeerImage" (
"id" STRING NOT NULL,
"beerPostId" STRING NOT NULL,
"path" STRING NOT NULL,
"alt" STRING NOT NULL,
"caption" STRING NOT NULL,
"createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMPTZ(3),
"postedById" STRING NOT NULL,
CONSTRAINT "BeerImage_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "BreweryImage" (
"id" STRING NOT NULL,
"breweryPostId" STRING NOT NULL,
"path" STRING NOT NULL,
"createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMPTZ(3),
"caption" STRING NOT NULL,
"alt" STRING NOT NULL,
"postedById" STRING NOT NULL,
CONSTRAINT "BreweryImage_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "User_username_key" ON "User"("username");
-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
-- AddForeignKey
ALTER TABLE "BeerPost" ADD CONSTRAINT "BeerPost_postedById_fkey" FOREIGN KEY ("postedById") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BeerPost" ADD CONSTRAINT "BeerPost_breweryId_fkey" FOREIGN KEY ("breweryId") REFERENCES "BreweryPost"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BeerPost" ADD CONSTRAINT "BeerPost_typeId_fkey" FOREIGN KEY ("typeId") REFERENCES "BeerType"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BeerPostLike" ADD CONSTRAINT "BeerPostLike_beerPostId_fkey" FOREIGN KEY ("beerPostId") REFERENCES "BeerPost"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BeerPostLike" ADD CONSTRAINT "BeerPostLike_likedById_fkey" FOREIGN KEY ("likedById") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BeerComment" ADD CONSTRAINT "BeerComment_beerPostId_fkey" FOREIGN KEY ("beerPostId") REFERENCES "BeerPost"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BeerComment" ADD CONSTRAINT "BeerComment_postedById_fkey" FOREIGN KEY ("postedById") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BeerType" ADD CONSTRAINT "BeerType_postedById_fkey" FOREIGN KEY ("postedById") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BreweryPost" ADD CONSTRAINT "BreweryPost_postedById_fkey" FOREIGN KEY ("postedById") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BreweryComment" ADD CONSTRAINT "BreweryComment_breweryPostId_fkey" FOREIGN KEY ("breweryPostId") REFERENCES "BreweryPost"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BreweryComment" ADD CONSTRAINT "BreweryComment_postedById_fkey" FOREIGN KEY ("postedById") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BeerImage" ADD CONSTRAINT "BeerImage_beerPostId_fkey" FOREIGN KEY ("beerPostId") REFERENCES "BeerPost"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BeerImage" ADD CONSTRAINT "BeerImage_postedById_fkey" FOREIGN KEY ("postedById") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BreweryImage" ADD CONSTRAINT "BreweryImage_breweryPostId_fkey" FOREIGN KEY ("breweryPostId") REFERENCES "BreweryPost"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BreweryImage" ADD CONSTRAINT "BreweryImage_postedById_fkey" FOREIGN KEY ("postedById") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

View File

@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "cockroachdb"

135
src/prisma/schema.prisma Normal file
View File

@@ -0,0 +1,135 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "cockroachdb"
url = env("DATABASE_URL")
}
model User {
id String @id @default(uuid())
username String @unique
firstName String
lastName String
hash String
email String @unique
createdAt DateTime @default(now()) @db.Timestamptz(3)
updatedAt DateTime? @updatedAt @db.Timestamptz(3)
isAccountVerified Boolean @default(false)
dateOfBirth DateTime
beerPosts BeerPost[]
beerTypes BeerType[]
breweryPosts BreweryPost[]
beerComments BeerComment[]
breweryComments BreweryComment[]
BeerPostLikes BeerPostLike[]
BeerImage BeerImage[]
BreweryImage BreweryImage[]
}
model BeerPost {
id String @id @default(uuid())
name String
ibu Float
abv Float
description String
postedBy User @relation(fields: [postedById], references: [id], onDelete: Cascade)
postedById String
brewery BreweryPost @relation(fields: [breweryId], references: [id], onDelete: Cascade)
breweryId String
type BeerType @relation(fields: [typeId], references: [id], onDelete: Cascade)
typeId String
createdAt DateTime @default(now()) @db.Timestamptz(3)
updatedAt DateTime? @updatedAt @db.Timestamptz(3)
beerComments BeerComment[]
beerImages BeerImage[]
BeerPostLikes BeerPostLike[]
}
model BeerPostLike {
id String @id @default(uuid())
beerPost BeerPost @relation(fields: [beerPostId], references: [id], onDelete: Cascade)
beerPostId String
likedBy User @relation(fields: [likedById], references: [id], onDelete: Cascade)
likedById String
createdAt DateTime @default(now()) @db.Timestamptz(3)
updatedAt DateTime? @updatedAt @db.Timestamptz(3)
}
model BeerComment {
id String @id @default(uuid())
rating Int
beerPost BeerPost @relation(fields: [beerPostId], references: [id], onDelete: Cascade)
beerPostId String
postedBy User @relation(fields: [postedById], references: [id], onDelete: Cascade)
postedById String
content String
createdAt DateTime @default(now()) @db.Timestamptz(3)
updatedAt DateTime? @updatedAt @db.Timestamptz(3)
}
model BeerType {
id String @id @default(uuid())
name String
createdAt DateTime @default(now()) @db.Timestamptz(3)
updatedAt DateTime? @updatedAt @db.Timestamptz(3)
postedBy User @relation(fields: [postedById], references: [id], onDelete: Cascade)
postedById String
beerPosts BeerPost[]
}
model BreweryPost {
id String @id @default(uuid())
name String
location String
beers BeerPost[]
description String
createdAt DateTime @default(now()) @db.Timestamptz(3)
updatedAt DateTime? @updatedAt @db.Timestamptz(3)
postedBy User @relation(fields: [postedById], references: [id], onDelete: Cascade)
postedById String
breweryComments BreweryComment[]
breweryImages BreweryImage[]
}
model BreweryComment {
id String @id @default(uuid())
rating Int
breweryPost BreweryPost @relation(fields: [breweryPostId], references: [id], onDelete: Cascade)
breweryPostId String
postedBy User @relation(fields: [postedById], references: [id], onDelete: Cascade)
postedById String
content String
createdAt DateTime @default(now()) @db.Timestamptz(3)
updatedAt DateTime? @updatedAt @db.Timestamptz(3)
}
model BeerImage {
id String @id @default(uuid())
beerPost BeerPost @relation(fields: [beerPostId], references: [id], onDelete: Cascade)
beerPostId String
path String
alt String
caption String
createdAt DateTime @default(now()) @db.Timestamptz(3)
updatedAt DateTime? @updatedAt @db.Timestamptz(3)
postedBy User @relation(fields: [postedById], references: [id], onDelete: Cascade)
postedById String
}
model BreweryImage {
id String @id @default(uuid())
breweryPost BreweryPost @relation(fields: [breweryPostId], references: [id], onDelete: Cascade)
breweryPostId String
path String
createdAt DateTime @default(now()) @db.Timestamptz(3)
updatedAt DateTime? @updatedAt @db.Timestamptz(3)
caption String
alt String
postedBy User @relation(fields: [postedById], references: [id], onDelete: Cascade)
postedById String
}

View File

@@ -0,0 +1,18 @@
import DBClient from '../../DBClient';
const cleanDatabase = async () => {
const prisma = DBClient.instance;
await prisma.$executeRaw`TRUNCATE TABLE "User" CASCADE`;
await prisma.$executeRaw`TRUNCATE TABLE "BeerPost" CASCADE`;
await prisma.$executeRaw`TRUNCATE TABLE "BeerType" CASCADE`;
await prisma.$executeRaw`TRUNCATE TABLE "BreweryPost" CASCADE`;
await prisma.$executeRaw`TRUNCATE TABLE "BeerComment" CASCADE`;
await prisma.$executeRaw`TRUNCATE TABLE "BreweryComment" CASCADE`;
await prisma.$executeRaw`TRUNCATE TABLE "BeerPostLike" CASCADE`;
await prisma.$executeRaw`TRUNCATE TABLE "BeerImage" CASCADE`;
await prisma.$executeRaw`TRUNCATE TABLE "BreweryImage" CASCADE`;
await prisma.$disconnect();
};
export default cleanDatabase;

View File

@@ -0,0 +1,43 @@
// eslint-disable-next-line import/no-extraneous-dependencies
import { faker } from '@faker-js/faker';
import { BeerPost, BeerImage, User } from '@prisma/client';
import DBClient from '../../DBClient';
interface CreateNewBeerImagesArgs {
numberOfImages: number;
joinData: { beerPosts: BeerPost[]; users: User[] };
}
const createNewBeerImages = async ({
numberOfImages,
joinData: { beerPosts, users },
}: CreateNewBeerImagesArgs) => {
const prisma = DBClient.instance;
const createdAt = faker.date.past(1);
const beerImagesPromises: Promise<BeerImage>[] = [];
// eslint-disable-next-line no-plusplus
for (let i = 0; i < numberOfImages; i++) {
const beerPost = beerPosts[Math.floor(Math.random() * beerPosts.length)];
const user = users[Math.floor(Math.random() * users.length)];
const caption = faker.lorem.sentence();
const alt = faker.lorem.sentence();
beerImagesPromises.push(
prisma.beerImage.create({
data: {
path: 'https://picsum.photos/5000/5000',
alt,
caption,
beerPost: { connect: { id: beerPost.id } },
postedBy: { connect: { id: user.id } },
createdAt,
},
}),
);
}
return Promise.all(beerImagesPromises);
};
export default createNewBeerImages;

View File

@@ -0,0 +1,42 @@
// eslint-disable-next-line import/no-extraneous-dependencies
import { faker } from '@faker-js/faker';
import { BeerComment, BeerPost, User } from '@prisma/client';
import DBClient from '../../DBClient';
interface CreateNewBeerCommentsArgs {
numberOfComments: number;
joinData: {
beerPosts: BeerPost[];
users: User[];
};
}
const createNewBeerComments = async ({
numberOfComments,
joinData,
}: CreateNewBeerCommentsArgs) => {
const { beerPosts, users } = joinData;
const prisma = DBClient.instance;
const beerCommentPromises: Promise<BeerComment>[] = [];
// eslint-disable-next-line no-plusplus
for (let i = 0; i < numberOfComments; i++) {
const content = faker.lorem.lines(5);
const user = users[Math.floor(Math.random() * users.length)];
const beerPost = beerPosts[Math.floor(Math.random() * beerPosts.length)];
const createdAt = faker.date.past(1);
beerCommentPromises.push(
prisma.beerComment.create({
data: {
content,
postedBy: { connect: { id: user.id } },
beerPost: { connect: { id: beerPost.id } },
rating: Math.floor(Math.random() * 5) + 1,
createdAt,
},
}),
);
}
return Promise.all(beerCommentPromises);
};
export default createNewBeerComments;

View File

@@ -0,0 +1,34 @@
import type { BeerPost, BeerPostLike, User } from '@prisma/client';
import DBClient from '../../DBClient';
const createNewBeerPostLikes = async ({
joinData: { beerPosts, users },
numberOfLikes,
}: {
joinData: {
beerPosts: BeerPost[];
users: User[];
};
numberOfLikes: number;
}) => {
const beerPostLikePromises: Promise<BeerPostLike>[] = [];
// eslint-disable-next-line no-plusplus
for (let i = 0; i < numberOfLikes; i++) {
const beerPost = beerPosts[Math.floor(Math.random() * beerPosts.length)];
const user = users[Math.floor(Math.random() * users.length)];
beerPostLikePromises.push(
DBClient.instance.beerPostLike.create({
data: {
beerPost: { connect: { id: beerPost.id } },
likedBy: { connect: { id: user.id } },
},
}),
);
}
return Promise.all(beerPostLikePromises);
};
export default createNewBeerPostLikes;

View File

@@ -0,0 +1,47 @@
// eslint-disable-next-line import/no-extraneous-dependencies
import { faker } from '@faker-js/faker';
import { User, BeerType, BreweryPost } from '@prisma/client';
import DBClient from '../../DBClient';
interface CreateNewBeerPostsArgs {
numberOfPosts: number;
joinData: {
users: User[];
breweryPosts: BreweryPost[];
beerTypes: BeerType[];
};
}
const createNewBeerPosts = async ({
numberOfPosts,
joinData,
}: CreateNewBeerPostsArgs) => {
const { users, breweryPosts, beerTypes } = joinData;
const prisma = DBClient.instance;
const beerPostPromises = [];
// eslint-disable-next-line no-plusplus
for (let i = 0; i < numberOfPosts; i++) {
const user = users[Math.floor(Math.random() * users.length)];
const beerType = beerTypes[Math.floor(Math.random() * beerTypes.length)];
const breweryPost = breweryPosts[Math.floor(Math.random() * breweryPosts.length)];
const createdAt = faker.date.past(1);
beerPostPromises.push(
prisma.beerPost.create({
data: {
abv: Math.floor(Math.random() * (12 - 4) + 4),
ibu: Math.floor(Math.random() * (60 - 10) + 10),
name: faker.commerce.productName(),
description: faker.lorem.lines(12).replace(/(\r\n|\n|\r)/gm, ' '),
brewery: { connect: { id: breweryPost.id } },
postedBy: { connect: { id: user.id } },
type: { connect: { id: beerType.id } },
createdAt,
},
}),
);
}
return Promise.all(beerPostPromises);
};
export default createNewBeerPosts;

View File

@@ -0,0 +1,52 @@
// eslint-disable-next-line import/no-extraneous-dependencies
import { faker } from '@faker-js/faker';
import { User, BeerType } from '@prisma/client';
import DBClient from '../../DBClient';
interface CreateNewBeerTypesArgs {
joinData: {
users: User[];
};
}
const createNewBeerTypes = async ({ joinData }: CreateNewBeerTypesArgs) => {
const { users } = joinData;
const prisma = DBClient.instance;
const beerTypePromises: Promise<BeerType>[] = [];
const types = [
'IPA',
'Pilsner',
'Stout',
'Lager',
'Wheat Beer',
'Belgian Ale',
'Pale Ale',
'Brown Ale',
'Sour Beer',
'Porter',
'Bock',
'Rauchbier',
'Sasion',
'Kolsch',
'Helles',
'Weizenbock',
'Doppelbock',
'Eisbock',
'Barley Wine',
];
types.forEach((type) => {
const user = users[Math.floor(Math.random() * users.length)];
const createdAt = faker.date.past(1);
beerTypePromises.push(
prisma.beerType.create({
data: { name: type, postedBy: { connect: { id: user.id } }, createdAt },
}),
);
});
return Promise.all(beerTypePromises);
};
export default createNewBeerTypes;

View File

@@ -0,0 +1,44 @@
// eslint-disable-next-line import/no-extraneous-dependencies
import { faker } from '@faker-js/faker';
import { BreweryPost, BreweryImage, User } from '@prisma/client';
import DBClient from '../../DBClient';
interface CreateBreweryImagesArgs {
numberOfImages: number;
joinData: {
breweryPosts: BreweryPost[];
users: User[];
};
}
const createNewBreweryImages = async ({
numberOfImages,
joinData: { breweryPosts, users },
}: CreateBreweryImagesArgs) => {
const prisma = DBClient.instance;
const createdAt = faker.date.past(1);
const breweryImagesPromises: Promise<BreweryImage>[] = [];
// eslint-disable-next-line no-plusplus
for (let i = 0; i < numberOfImages; i++) {
const breweryPost = breweryPosts[Math.floor(Math.random() * breweryPosts.length)];
const user = users[Math.floor(Math.random() * users.length)];
breweryImagesPromises.push(
prisma.breweryImage.create({
data: {
path: 'https://picsum.photos/5000/5000',
alt: 'Placeholder brewery image.',
caption: 'Placeholder brewery image caption.',
breweryPost: { connect: { id: breweryPost.id } },
postedBy: { connect: { id: user.id } },
createdAt,
},
}),
);
}
return Promise.all(breweryImagesPromises);
};
export default createNewBreweryImages;

View File

@@ -0,0 +1,42 @@
// eslint-disable-next-line import/no-extraneous-dependencies
import { faker } from '@faker-js/faker';
import { BreweryComment, BreweryPost, User } from '@prisma/client';
import DBClient from '../../DBClient';
interface CreateNewBreweryPostCommentsArgs {
numberOfComments: number;
joinData: {
breweryPosts: BreweryPost[];
users: User[];
};
}
const createNewBreweryPostComments = async ({
numberOfComments,
joinData,
}: CreateNewBreweryPostCommentsArgs) => {
const { breweryPosts, users } = joinData;
const prisma = DBClient.instance;
const breweryCommentPromises: Promise<BreweryComment>[] = [];
const createdAt = faker.date.past(1);
// eslint-disable-next-line no-plusplus
for (let i = 0; i < numberOfComments; i++) {
const content = faker.lorem.lines(5);
const user = users[Math.floor(Math.random() * users.length)];
const breweryPost = breweryPosts[Math.floor(Math.random() * breweryPosts.length)];
breweryCommentPromises.push(
prisma.breweryComment.create({
data: {
content,
postedBy: { connect: { id: user.id } },
breweryPost: { connect: { id: breweryPost.id } },
rating: Math.floor(Math.random() * 5) + 1,
createdAt,
},
}),
);
}
return Promise.all(breweryCommentPromises);
};
export default createNewBreweryPostComments;

View File

@@ -0,0 +1,42 @@
// eslint-disable-next-line import/no-extraneous-dependencies
import { faker } from '@faker-js/faker';
import { User } from '@prisma/client';
import DBClient from '../../DBClient';
interface CreateNewBreweryPostsArgs {
numberOfPosts: number;
joinData: {
users: User[];
};
}
const createNewBreweryPosts = async ({
numberOfPosts,
joinData,
}: CreateNewBreweryPostsArgs) => {
const { users } = joinData;
const prisma = DBClient.instance;
const breweryPromises = [];
// eslint-disable-next-line no-plusplus
for (let i = 0; i < numberOfPosts; i++) {
const name = `${faker.commerce.productName()} Brewing Company`;
const location = faker.address.cityName();
const description = faker.lorem.lines(5);
const user = users[Math.floor(Math.random() * users.length)];
const createdAt = faker.date.past(1);
breweryPromises.push(
prisma.breweryPost.create({
data: {
name,
location,
description,
postedBy: { connect: { id: user.id } },
createdAt,
},
}),
);
}
return Promise.all(breweryPromises);
};
export default createNewBreweryPosts;

View File

@@ -0,0 +1,47 @@
import argon2 from 'argon2';
// eslint-disable-next-line import/no-extraneous-dependencies
import { faker } from '@faker-js/faker';
import crypto from 'crypto';
import DBClient from '../../DBClient';
interface CreateNewUsersArgs {
numberOfUsers: number;
}
const createNewUsers = async ({ numberOfUsers }: CreateNewUsersArgs) => {
const prisma = DBClient.instance;
const userPromises = [];
const hashedPasswords = await Promise.all(
Array.from({ length: numberOfUsers }, () => argon2.hash(faker.internet.password())),
);
// eslint-disable-next-line no-plusplus
for (let i = 0; i < numberOfUsers; i++) {
const randomValue = crypto.randomBytes(10).toString('hex');
const firstName = faker.name.firstName();
const lastName = faker.name.lastName();
const username = `${firstName[0]}.${lastName}.${randomValue}`;
const email = faker.internet.email(firstName, randomValue, 'example.com');
const hash = hashedPasswords[i];
const dateOfBirth = faker.date.birthdate({ mode: 'age', min: 19 });
const createdAt = faker.date.past(1);
userPromises.push(
prisma.user.create({
data: {
firstName,
lastName,
email,
username,
dateOfBirth,
createdAt,
hash,
},
}),
);
}
return Promise.all(userPromises);
};
export default createNewUsers;

90
src/prisma/seed/index.ts Normal file
View File

@@ -0,0 +1,90 @@
import { performance } from 'perf_hooks';
import logger from '../../config/pino/logger';
import cleanDatabase from './clean/cleanDatabase';
import createNewBeerImages from './create/createNewBeerImages';
import createNewBeerPostComments from './create/createNewBeerPostComments';
import createNewBeerPostLikes from './create/createNewBeerPostLikes';
import createNewBeerPosts from './create/createNewBeerPosts';
import createNewBeerTypes from './create/createNewBeerTypes';
import createNewBreweryImages from './create/createNewBreweryImages';
import createNewBreweryPostComments from './create/createNewBreweryPostComments';
import createNewBreweryPosts from './create/createNewBreweryPosts';
import createNewUsers from './create/createNewUsers';
(async () => {
try {
const start = performance.now();
logger.info('Clearing database.');
await cleanDatabase();
logger.info('Database cleared successfully, preparing to seed.');
const users = await createNewUsers({ numberOfUsers: 1000 });
const [breweryPosts, beerTypes] = await Promise.all([
createNewBreweryPosts({ numberOfPosts: 100, joinData: { users } }),
createNewBeerTypes({ joinData: { users } }),
]);
const beerPosts = await createNewBeerPosts({
numberOfPosts: 200,
joinData: { breweryPosts, beerTypes, users },
});
const [
beerPostComments,
breweryPostComments,
beerPostLikes,
beerImages,
breweryImages,
] = await Promise.all([
createNewBeerPostComments({
numberOfComments: 45000,
joinData: { beerPosts, users },
}),
createNewBreweryPostComments({
numberOfComments: 45000,
joinData: { breweryPosts, users },
}),
createNewBeerPostLikes({
numberOfLikes: 10000,
joinData: { beerPosts, users },
}),
createNewBeerImages({
numberOfImages: 1000,
joinData: { beerPosts, users },
}),
createNewBreweryImages({
numberOfImages: 1000,
joinData: { breweryPosts, users },
}),
]);
const end = performance.now();
const timeElapsed = (end - start) / 1000;
logger.info('Database seeded successfully.');
logger.info({
numberOfUsers: users.length,
numberOfBreweryPosts: breweryPosts.length,
numberOfBeerPosts: beerPosts.length,
numberOfBeerTypes: beerTypes.length,
numberOfBeerPostLikes: beerPostLikes.length,
numberOfBeerPostComments: beerPostComments.length,
numberOfBreweryPostComments: breweryPostComments.length,
numberOfBeerImages: beerImages.length,
numberOfBreweryImages: breweryImages.length,
});
logger.info(`Database seeded in ${timeElapsed.toFixed(2)} seconds.`);
process.exit(0);
} catch (error) {
logger.error('Error seeding database.');
logger.error(error);
process.exit(1);
}
})();

Some files were not shown because too many files have changed in this diff Show More