Add edit beer post, 500 page, and redirectIfLoggedIn getServerSideProps.

Implement edit beer post functionality.

Register, edit and create beer post forms are now using the same layout found in components/ui/forms/BeerPostFormPageLayout. All forms are now extracted into their own components and are now found in components.

Added redirectIfLoggedIn getServerSidesProp fn for login and register pages.
This commit is contained in:
Aaron William Po
2023-02-27 18:13:38 -05:00
parent 11b3304c54
commit 7126c74d5d
18 changed files with 588 additions and 283 deletions

20
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;

View 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;

View File

@@ -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 } };
},
);

View File

@@ -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>
);
};

View File

@@ -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>
);
};

View File

@@ -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,
});

View File

@@ -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,
});

View File

@@ -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';