mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 10:42:08 +00:00
Merge pull request #9 from aaronpo97/dev
Add edit beer post, 500 page, and redirectIfLoggedIn getServerSideProps.
This commit is contained in:
@@ -17,19 +17,14 @@ import FormSelect from './ui/forms/FormSelect';
|
||||
import FormTextArea from './ui/forms/FormTextArea';
|
||||
import FormTextInput from './ui/forms/FormTextInput';
|
||||
|
||||
type BeerPostT = z.infer<typeof CreateBeerPostValidationSchema>;
|
||||
type CreateBeerPostSchema = z.infer<typeof CreateBeerPostValidationSchema>;
|
||||
|
||||
interface BeerFormProps {
|
||||
formType: 'edit' | 'create';
|
||||
// eslint-disable-next-line react/require-default-props
|
||||
defaultValues?: BeerPostT;
|
||||
breweries?: BreweryPostQueryResult[];
|
||||
types?: BeerType[];
|
||||
breweries: BreweryPostQueryResult[];
|
||||
types: BeerType[];
|
||||
}
|
||||
|
||||
const BeerForm: FunctionComponent<BeerFormProps> = ({
|
||||
formType,
|
||||
defaultValues,
|
||||
const CreateBeerPostForm: FunctionComponent<BeerFormProps> = ({
|
||||
breweries = [],
|
||||
types = [],
|
||||
}) => {
|
||||
@@ -37,47 +32,30 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm<BeerPostT>({
|
||||
} = useForm<CreateBeerPostSchema>({
|
||||
resolver: zodResolver(CreateBeerPostValidationSchema),
|
||||
defaultValues: {
|
||||
name: defaultValues?.name,
|
||||
description: defaultValues?.description,
|
||||
abv: defaultValues?.abv,
|
||||
ibu: defaultValues?.ibu,
|
||||
},
|
||||
});
|
||||
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const onSubmit: SubmitHandler<BeerPostT> = async (data) => {
|
||||
setIsSubmitting(true);
|
||||
switch (formType) {
|
||||
case 'create': {
|
||||
try {
|
||||
const response = await sendCreateBeerPostRequest(data);
|
||||
router.push(`/beers/${response.id}`);
|
||||
break;
|
||||
} catch (e) {
|
||||
if (e instanceof Error) {
|
||||
setError(e.message);
|
||||
}
|
||||
break;
|
||||
}
|
||||
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;
|
||||
}
|
||||
case 'edit':
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
setError(e.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form className="form-control" onSubmit={handleSubmit(onSubmit)}>
|
||||
<div className="my-5">
|
||||
{error && <ErrorAlert error={error} setError={setError} />}
|
||||
</div>
|
||||
<div>{error && <ErrorAlert error={error} setError={setError} />}</div>
|
||||
<FormInfo>
|
||||
<FormLabel htmlFor="name">Name</FormLabel>
|
||||
<FormError>{errors.name?.message}</FormError>
|
||||
@@ -92,8 +70,9 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
||||
disabled={isSubmitting}
|
||||
/>
|
||||
</FormSegment>
|
||||
{formType === 'create' && breweries.length && (
|
||||
<>
|
||||
|
||||
<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>
|
||||
@@ -112,10 +91,30 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
||||
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 sm:text-xs md:mb-3">
|
||||
<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>
|
||||
@@ -161,44 +160,13 @@ const BeerForm: FunctionComponent<BeerFormProps> = ({
|
||||
/>
|
||||
</FormSegment>
|
||||
|
||||
{formType === 'create' && types.length && (
|
||||
<>
|
||||
<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>
|
||||
</>
|
||||
)}
|
||||
|
||||
{!isSubmitting && (
|
||||
<Button type="submit" isSubmitting={isSubmitting}>{`${
|
||||
formType === 'edit'
|
||||
? `Edit ${defaultValues?.name || 'beer post'}`
|
||||
: 'Create beer post'
|
||||
}`}</Button>
|
||||
)}
|
||||
|
||||
{isSubmitting && (
|
||||
<div className="mt-6">
|
||||
<Button type="submit" isSubmitting={isSubmitting}>
|
||||
Submitting
|
||||
{isSubmitting ? 'Submitting...' : 'Submit'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
};
|
||||
|
||||
export default BeerForm;
|
||||
export default CreateBeerPostForm;
|
||||
141
components/EditBeerPostForm.tsx
Normal file
141
components/EditBeerPostForm.tsx
Normal file
@@ -0,0 +1,141 @@
|
||||
import sendEditBeerPostRequest from '@/requests/sendEditBeerPostRequest';
|
||||
import EditBeerPostValidationSchema from '@/services/BeerPost/schema/EditBeerPostValidationSchema';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import Link from 'next/link';
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form className="form-control" onSubmit={handleSubmit(onSubmit)}>
|
||||
<div className="my-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-6 flex w-full space-x-6">
|
||||
<div className="w-3/6">
|
||||
<Link
|
||||
className={`btn-primary btn w-full rounded-xl ${
|
||||
isSubmitting ? 'loading' : ''
|
||||
}`}
|
||||
href={`/beers/${previousValues.id}`}
|
||||
>
|
||||
Discard Changes
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="w-3/6">
|
||||
<Button type="submit" isSubmitting={isSubmitting}>
|
||||
{isSubmitting ? 'Submitting...' : 'Submit'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
};
|
||||
|
||||
export default EditBeerPostForm;
|
||||
171
components/RegisterUserForm.tsx
Normal file
171
components/RegisterUserForm.tsx
Normal file
@@ -0,0 +1,171 @@
|
||||
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
|
||||
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
|
||||
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
|
||||
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
|
||||
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
|
||||
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
|
||||
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"
|
||||
type="date"
|
||||
formValidationSchema={register('dateOfBirth')}
|
||||
error={!!errors.dateOfBirth}
|
||||
placeholder="date of birth"
|
||||
/>
|
||||
</FormSegment>
|
||||
<div className="mt-6 w-full">
|
||||
<Button type="submit">Register User</Button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
};
|
||||
|
||||
export default RegisterUserForm;
|
||||
28
components/ui/forms/BeerPostFormPageLayout.tsx
Normal file
28
components/ui/forms/BeerPostFormPageLayout.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
import { ReactNode, FC } from 'react';
|
||||
import { IconType } from 'react-icons';
|
||||
|
||||
interface FormPageLayoutProps {
|
||||
children: ReactNode;
|
||||
headingText: string;
|
||||
headingIcon: IconType;
|
||||
}
|
||||
|
||||
const FormPageLayout: FC<FormPageLayoutProps> = ({
|
||||
children: FormComponent,
|
||||
headingIcon,
|
||||
headingText,
|
||||
}) => {
|
||||
return (
|
||||
<div className="align-center my-20 flex h-fit flex-col items-center justify-center">
|
||||
<div className="w-8/12">
|
||||
<div className="my-4 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;
|
||||
@@ -14,7 +14,7 @@ const Button: FunctionComponent<FormButtonProps> = ({
|
||||
// eslint-disable-next-line react/button-has-type
|
||||
<button
|
||||
type={type}
|
||||
className={`btn btn-primary mt-4 w-full rounded-xl ${isSubmitting ? 'loading' : ''}`}
|
||||
className={`btn-primary btn w-full rounded-xl ${isSubmitting ? 'loading' : ''}`}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
|
||||
18
getServerSideProps/redirectIfLoggedIn.ts
Normal file
18
getServerSideProps/redirectIfLoggedIn.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { GetServerSideProps, GetServerSidePropsContext, Redirect } from 'next';
|
||||
import { getLoginSession } from '@/config/auth/session';
|
||||
|
||||
const redirectIfLoggedIn = (redirect: Redirect) => {
|
||||
const fn: GetServerSideProps = async (context: GetServerSidePropsContext) => {
|
||||
try {
|
||||
const { req } = context;
|
||||
await getLoginSession(req);
|
||||
return { redirect };
|
||||
} catch {
|
||||
return { props: {} };
|
||||
}
|
||||
};
|
||||
|
||||
return fn;
|
||||
};
|
||||
|
||||
export default redirectIfLoggedIn;
|
||||
@@ -1,6 +1,6 @@
|
||||
import { GetServerSidePropsContext, GetServerSidePropsResult, PreviewData } from 'next';
|
||||
import { ParsedUrlQuery } from 'querystring';
|
||||
import { getLoginSession } from './session';
|
||||
import { getLoginSession } from '../config/auth/session';
|
||||
|
||||
export type ExtendedGetServerSideProps<
|
||||
P extends { [key: string]: any } = { [key: string]: any },
|
||||
20
pages/500.tsx
Normal file
20
pages/500.tsx
Normal 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;
|
||||
55
pages/api/beers/[id]/index.ts
Normal file
55
pages/api/beers/[id]/index.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
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 } from 'next-connect';
|
||||
import { z } from 'zod';
|
||||
import ServerError from '@/config/util/ServerError';
|
||||
|
||||
interface EditBeerPostRequest extends UserExtendedNextApiRequest {
|
||||
query: { id: string };
|
||||
body: z.infer<typeof EditBeerPostValidationSchema>;
|
||||
}
|
||||
|
||||
const editBeerPost = async (
|
||||
req: EditBeerPostRequest,
|
||||
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
|
||||
) => {
|
||||
const { body, 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);
|
||||
}
|
||||
|
||||
const updated = await editBeerPostById(id, body);
|
||||
|
||||
console.log(updated);
|
||||
|
||||
res.status(200).json({
|
||||
message: 'Beer post updated successfully',
|
||||
success: true,
|
||||
statusCode: 200,
|
||||
});
|
||||
};
|
||||
|
||||
const router = createRouter<
|
||||
EditBeerPostRequest,
|
||||
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
|
||||
>();
|
||||
|
||||
router.put(getCurrentUser, editBeerPost);
|
||||
|
||||
const handler = router.handler(NextConnectOptions);
|
||||
|
||||
export default handler;
|
||||
@@ -1,23 +1,40 @@
|
||||
import { NextPage } from 'next';
|
||||
import Head from 'next/head';
|
||||
import React from 'react';
|
||||
|
||||
import Layout from '@/components/ui/Layout';
|
||||
import { NextPage } from 'next';
|
||||
import withPageAuthRequired from '@/config/auth/withPageAuthRequired';
|
||||
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/BeerPostFormPageLayout';
|
||||
import { BiBeer } from 'react-icons/bi';
|
||||
|
||||
interface EditPageProps {
|
||||
beerPost: BeerPostQueryResult;
|
||||
}
|
||||
|
||||
const EditPage: NextPage<EditPageProps> = ({ beerPost }) => {
|
||||
const pageTitle = `Edit "${beerPost.name}"`;
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<Head>
|
||||
<title>Edit {beerPost.name}</title>
|
||||
<meta name="description" content={`Edit ${beerPost.name}`} />
|
||||
<title>{pageTitle}</title>
|
||||
<meta name="description" content={pageTitle} />
|
||||
</Head>
|
||||
|
||||
<FormPageLayout headingText={pageTitle} headingIcon={BiBeer}>
|
||||
<EditBeerPostForm
|
||||
previousValues={{
|
||||
name: beerPost.name,
|
||||
abv: beerPost.abv,
|
||||
ibu: beerPost.ibu,
|
||||
description: beerPost.description,
|
||||
id: beerPost.id,
|
||||
}}
|
||||
/>
|
||||
</FormPageLayout>
|
||||
</Layout>
|
||||
);
|
||||
};
|
||||
@@ -36,16 +53,8 @@ export const getServerSideProps = withPageAuthRequired<EditPageProps>(
|
||||
|
||||
const isBeerPostOwner = beerPost.postedBy.id === userId;
|
||||
|
||||
if (!isBeerPostOwner) {
|
||||
return {
|
||||
redirect: { destination: `/beers/${beerPostId}`, permanent: false },
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
props: {
|
||||
beerPost: JSON.parse(JSON.stringify(beerPost)),
|
||||
},
|
||||
};
|
||||
return isBeerPostOwner
|
||||
? { props: { beerPost: JSON.parse(JSON.stringify(beerPost)) } }
|
||||
: { redirect: { destination: `/beers/${beerPostId}`, permanent: false } };
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import BeerForm from '@/components/BeerForm';
|
||||
import CreateBeerPostForm from '@/components/CreateBeerPostForm';
|
||||
import FormPageLayout from '@/components/ui/forms/BeerPostFormPageLayout';
|
||||
import Layout from '@/components/ui/Layout';
|
||||
import withPageAuthRequired from '@/config/auth/withPageAuthRequired';
|
||||
|
||||
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';
|
||||
|
||||
interface CreateBeerPageProps {
|
||||
@@ -18,15 +17,9 @@ interface CreateBeerPageProps {
|
||||
const Create: NextPage<CreateBeerPageProps> = ({ breweries, types }) => {
|
||||
return (
|
||||
<Layout>
|
||||
<div className="align-center my-20 flex h-fit flex-col items-center justify-center">
|
||||
<div className="w-8/12">
|
||||
<div className="flex flex-col items-center space-y-1">
|
||||
<BiBeer className="text-5xl" />
|
||||
<h1 className="text-3xl font-bold">Create a New Beer</h1>
|
||||
</div>
|
||||
<BeerForm formType="create" breweries={breweries} types={types} />
|
||||
</div>
|
||||
</div>
|
||||
<FormPageLayout headingText="Create a new beer" headingIcon={BiBeer}>
|
||||
<CreateBeerPostForm breweries={breweries} types={types} />
|
||||
</FormPageLayout>
|
||||
</Layout>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import Layout from '@/components/ui/Layout';
|
||||
import { BeerPostQueryResult } from '@/services/BeerPost/schema/BeerPostQueryResult';
|
||||
import getBreweryPostById from '@/services/BreweryPost/getBreweryPostById';
|
||||
import { GetServerSideProps, NextPage } from 'next';
|
||||
@@ -8,9 +9,9 @@ interface BreweryPageProps {
|
||||
|
||||
const BreweryByIdPage: NextPage<BreweryPageProps> = ({ breweryPost }) => {
|
||||
return (
|
||||
<>
|
||||
<Layout>
|
||||
<h1 className="text-3xl font-bold underline">{breweryPost.name}</h1>
|
||||
</>
|
||||
</Layout>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,27 +1,14 @@
|
||||
import { NextPage } from 'next';
|
||||
import { useEffect } from 'react';
|
||||
import { useRouter } from 'next/router';
|
||||
import Layout from '@/components/ui/Layout';
|
||||
import useUser from '@/hooks/useUser';
|
||||
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 redirectIfLoggedIn from '@/getServerSideProps/redirectIfLoggedIn';
|
||||
|
||||
const LoginPage: NextPage = () => {
|
||||
const { user } = useUser();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
if (!user) {
|
||||
return;
|
||||
}
|
||||
|
||||
router.push(`/user/current`);
|
||||
}, [user, router]);
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<Head>
|
||||
@@ -65,3 +52,8 @@ const LoginPage: NextPage = () => {
|
||||
};
|
||||
|
||||
export default LoginPage;
|
||||
|
||||
export const getServerSideProps = redirectIfLoggedIn({
|
||||
destination: '/',
|
||||
permanent: false,
|
||||
});
|
||||
|
||||
@@ -1,168 +1,28 @@
|
||||
import ErrorAlert from '@/components/ui/alerts/ErrorAlert';
|
||||
import Button from '@/components/ui/forms/Button';
|
||||
import FormError from '@/components/ui/forms/FormError';
|
||||
import FormInfo from '@/components/ui/forms/FormInfo';
|
||||
import FormLabel from '@/components/ui/forms/FormLabel';
|
||||
import FormSegment from '@/components/ui/forms/FormSegment';
|
||||
import FormTextInput from '@/components/ui/forms/FormTextInput';
|
||||
import RegisterUserForm from '@/components/RegisterUserForm';
|
||||
import FormPageLayout from '@/components/ui/forms/BeerPostFormPageLayout';
|
||||
import Layout from '@/components/ui/Layout';
|
||||
import sendRegisterUserRequest from '@/requests/sendRegisterUserRequest';
|
||||
import CreateUserValidationSchema from '@/services/User/schema/CreateUserValidationSchema';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import redirectIfLoggedIn from '@/getServerSideProps/redirectIfLoggedIn';
|
||||
import { NextPage } from 'next';
|
||||
import { useRouter } from 'next/router';
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { FaUserCircle } from 'react-icons/fa';
|
||||
import { z } from 'zod';
|
||||
|
||||
interface RegisterUserProps {}
|
||||
|
||||
const RegisterUserPage: NextPage<RegisterUserProps> = () => {
|
||||
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.',
|
||||
);
|
||||
}
|
||||
};
|
||||
import Head from 'next/head';
|
||||
import { BiUser } from 'react-icons/bi';
|
||||
|
||||
const RegisterUserPage: NextPage = () => {
|
||||
return (
|
||||
<Layout>
|
||||
<div
|
||||
className="flex h-full flex-col items-center justify-center space-y-6"
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
>
|
||||
<div className="flex flex-col items-center space-y-2">
|
||||
<FaUserCircle className="text-3xl" />
|
||||
<h1 className="text-4xl font-bold">Register</h1>
|
||||
</div>
|
||||
<form className="form-control w-7/12 space-y-5" noValidate>
|
||||
{serverResponseError && (
|
||||
<ErrorAlert error={serverResponseError} setError={setServerResponseError} />
|
||||
)}
|
||||
<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
|
||||
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
|
||||
id="lastName"
|
||||
type="text"
|
||||
formValidationSchema={register('lastName')}
|
||||
error={!!errors.lastName}
|
||||
placeholder="last name"
|
||||
/>
|
||||
</FormSegment>
|
||||
</div>
|
||||
</div>
|
||||
<FormInfo>
|
||||
<FormLabel htmlFor="username">username</FormLabel>
|
||||
<FormError>{errors.username?.message}</FormError>
|
||||
</FormInfo>
|
||||
<FormSegment>
|
||||
<FormTextInput
|
||||
id="username"
|
||||
type="text"
|
||||
formValidationSchema={register('username')}
|
||||
error={!!errors.username}
|
||||
placeholder="username"
|
||||
/>
|
||||
</FormSegment>
|
||||
<FormInfo>
|
||||
<FormLabel htmlFor="email">email</FormLabel>
|
||||
<FormError>{errors.email?.message}</FormError>
|
||||
</FormInfo>
|
||||
<FormSegment>
|
||||
<FormTextInput
|
||||
id="email"
|
||||
type="email"
|
||||
formValidationSchema={register('email')}
|
||||
error={!!errors.email}
|
||||
placeholder="email"
|
||||
/>
|
||||
</FormSegment>
|
||||
<FormInfo>
|
||||
<FormLabel htmlFor="password">password</FormLabel>
|
||||
<FormError>{errors.password?.message}</FormError>
|
||||
</FormInfo>
|
||||
<FormSegment>
|
||||
<FormTextInput
|
||||
id="password"
|
||||
type="password"
|
||||
formValidationSchema={register('password')}
|
||||
error={!!errors.password}
|
||||
placeholder="password"
|
||||
/>
|
||||
</FormSegment>
|
||||
<FormInfo>
|
||||
<FormLabel htmlFor="confirmPassword">confirm password</FormLabel>
|
||||
<FormError>{errors.confirmPassword?.message}</FormError>
|
||||
</FormInfo>
|
||||
<FormSegment>
|
||||
<FormTextInput
|
||||
id="confirmPassword"
|
||||
type="password"
|
||||
formValidationSchema={register('confirmPassword')}
|
||||
error={!!errors.confirmPassword}
|
||||
placeholder="confirm password"
|
||||
/>
|
||||
</FormSegment>
|
||||
<FormInfo>
|
||||
<FormLabel htmlFor="dateOfBirth">Date of birth</FormLabel>
|
||||
<FormError>{errors.dateOfBirth?.message}</FormError>
|
||||
</FormInfo>
|
||||
<FormSegment>
|
||||
<FormTextInput
|
||||
id="dateOfBirth"
|
||||
type="date"
|
||||
formValidationSchema={register('dateOfBirth')}
|
||||
error={!!errors.dateOfBirth}
|
||||
placeholder="date of birth"
|
||||
/>
|
||||
</FormSegment>
|
||||
<Button type="submit">Register User</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<Head>
|
||||
<title>Register User</title>
|
||||
<meta name="description" content="Register a new user" />
|
||||
</Head>
|
||||
<FormPageLayout headingText="Register User" headingIcon={BiUser}>
|
||||
<RegisterUserForm />
|
||||
</FormPageLayout>
|
||||
</Layout>
|
||||
);
|
||||
};
|
||||
|
||||
export default RegisterUserPage;
|
||||
|
||||
export const getServerSideProps = redirectIfLoggedIn({
|
||||
destination: '/',
|
||||
permanent: false,
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import Layout from '@/components/ui/Layout';
|
||||
import Spinner from '@/components/ui/Spinner';
|
||||
import withPageAuthRequired from '@/config/auth/withPageAuthRequired';
|
||||
import withPageAuthRequired from '@/getServerSideProps/withPageAuthRequired';
|
||||
import UserContext from '@/contexts/userContext';
|
||||
|
||||
import { GetServerSideProps, NextPage } from 'next';
|
||||
|
||||
26
requests/sendEditBeerPostRequest.ts
Normal file
26
requests/sendEditBeerPostRequest.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import EditBeerPostValidationSchema from '@/services/BeerPost/schema/EditBeerPostValidationSchema';
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
import { z } from 'zod';
|
||||
|
||||
async function sendEditBeerPostRequest(
|
||||
data: z.infer<typeof EditBeerPostValidationSchema>,
|
||||
) {
|
||||
const response = await fetch(`/api/beers/${data.id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('something went wrong');
|
||||
}
|
||||
|
||||
const json = await response.json();
|
||||
const parsed = APIResponseValidationSchema.safeParse(json);
|
||||
|
||||
if (!parsed.success) {
|
||||
throw new Error(parsed.error.message);
|
||||
}
|
||||
}
|
||||
|
||||
export default sendEditBeerPostRequest;
|
||||
14
services/BeerPost/editBeerPostById.ts
Normal file
14
services/BeerPost/editBeerPostById.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import { z } from 'zod';
|
||||
import EditBeerPostValidationSchema from './schema/EditBeerPostValidationSchema';
|
||||
|
||||
const schema = EditBeerPostValidationSchema.omit({ id: true });
|
||||
|
||||
export default async function editBeerPostById(id: string, data: z.infer<typeof schema>) {
|
||||
const beerPost = await DBClient.instance.beerPost.update({
|
||||
where: { id },
|
||||
data,
|
||||
});
|
||||
|
||||
return beerPost;
|
||||
}
|
||||
9
services/BeerPost/schema/EditBeerPostValidationSchema.ts
Normal file
9
services/BeerPost/schema/EditBeerPostValidationSchema.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { z } from 'zod';
|
||||
import CreateBeerPostValidationSchema from './CreateBeerPostValidationSchema';
|
||||
|
||||
const EditBeerPostValidationSchema = CreateBeerPostValidationSchema.omit({
|
||||
breweryId: true,
|
||||
typeId: true,
|
||||
}).extend({ id: z.string().uuid() });
|
||||
|
||||
export default EditBeerPostValidationSchema;
|
||||
Reference in New Issue
Block a user