mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 10:42:08 +00:00
@@ -51,7 +51,9 @@ const BeerCard: FC<{ post: z.infer<typeof beerPostQueryResult> }> = ({ post }) =
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
{!!user && <BeerPostLikeButton beerPostId={post.id} mutateCount={mutate} />}
|
||||
{!!user && !isLoading && (
|
||||
<BeerPostLikeButton beerPostId={post.id} mutateCount={mutate} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { FC, useMemo } from 'react';
|
||||
import Map, { Marker } from 'react-map-gl';
|
||||
|
||||
import LocationMarker from '../ui/LocationMarker';
|
||||
import ControlPanel from '../ui/maps/ControlPanel';
|
||||
|
||||
interface BreweryMapProps {
|
||||
latitude: number;
|
||||
@@ -45,6 +46,7 @@ const BreweryPostMap: FC<BreweryMapProps> = ({ latitude, longitude }) => {
|
||||
mapboxAccessToken={process.env.NEXT_PUBLIC_MAPBOX_ACCESS_TOKEN as string}
|
||||
scrollZoom
|
||||
>
|
||||
<ControlPanel />
|
||||
{pin}
|
||||
</Map>
|
||||
</div>
|
||||
|
||||
@@ -41,7 +41,7 @@ const BreweryCard: FC<{ brewery: z.infer<typeof BreweryPostQueryResult> }> = ({
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
{!isLoading && <span>liked by {likeCount} users</span>}
|
||||
{user && (
|
||||
{!!user && !isLoading && (
|
||||
<BreweryPostLikeButton breweryPostId={brewery.id} mutateCount={mutate} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import sendRegisterUserRequest from '@/requests/sendRegisterUserRequest';
|
||||
import CreateUserValidationSchema from '@/services/User/schema/CreateUserValidationSchema';
|
||||
import CreateUserValidationSchema, {
|
||||
CreateUserValidationSchemaWithUsernameAndEmailCheck,
|
||||
} from '@/services/User/schema/CreateUserValidationSchema';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useRouter } from 'next/router';
|
||||
import { FC, useState } from 'react';
|
||||
@@ -18,7 +20,7 @@ const RegisterUserForm: FC = () => {
|
||||
const router = useRouter();
|
||||
const { reset, register, handleSubmit, formState } = useForm<
|
||||
z.infer<typeof CreateUserValidationSchema>
|
||||
>({ resolver: zodResolver(CreateUserValidationSchema) });
|
||||
>({ resolver: zodResolver(CreateUserValidationSchemaWithUsernameAndEmailCheck) });
|
||||
|
||||
const { errors } = formState;
|
||||
const [serverResponseError, setServerResponseError] = useState('');
|
||||
|
||||
@@ -7,14 +7,14 @@ interface LocationMarkerProps {
|
||||
}
|
||||
|
||||
const sizeClasses: Record<NonNullable<LocationMarkerProps['size']>, `text-${string}`> = {
|
||||
sm: 'text-2xl',
|
||||
md: 'text-3xl',
|
||||
lg: 'text-4xl',
|
||||
xl: 'text-5xl',
|
||||
sm: 'text-lg',
|
||||
md: 'text-xl',
|
||||
lg: 'text-2xl',
|
||||
xl: 'text-3xl',
|
||||
};
|
||||
|
||||
const LocationMarker: FC<LocationMarkerProps> = ({ size = 'md', color = 'blue' }) => {
|
||||
return <HiLocationMarker className={`${sizeClasses[size]} text-${color}-400`} />;
|
||||
return <HiLocationMarker className={`${sizeClasses[size]} text-${color}-600`} />;
|
||||
};
|
||||
|
||||
export default React.memo(LocationMarker);
|
||||
|
||||
12
src/components/ui/maps/ControlPanel.tsx
Normal file
12
src/components/ui/maps/ControlPanel.tsx
Normal file
@@ -0,0 +1,12 @@
|
||||
import { FC, memo } from 'react';
|
||||
import { FullscreenControl, NavigationControl, ScaleControl } from 'react-map-gl';
|
||||
|
||||
const ControlPanel: FC = () => (
|
||||
<>
|
||||
<FullscreenControl position="top-left" />
|
||||
<NavigationControl position="top-left" />
|
||||
<ScaleControl />
|
||||
</>
|
||||
);
|
||||
|
||||
export default memo(ControlPanel);
|
||||
@@ -3,6 +3,11 @@ import { NextApiRequest, NextApiResponse } from 'next';
|
||||
import { NextHandler } from 'next-connect';
|
||||
import { z } from 'zod';
|
||||
|
||||
interface ValidateRequestArgs {
|
||||
bodySchema?: z.ZodSchema<any>;
|
||||
querySchema?: z.ZodSchema<any>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware to validate the request body and/or query against a zod schema.
|
||||
*
|
||||
@@ -18,15 +23,8 @@ import { z } from 'zod';
|
||||
* @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) => {
|
||||
const validateRequest = ({ bodySchema, querySchema }: ValidateRequestArgs) => {
|
||||
return (req: NextApiRequest, res: NextApiResponse, next: NextHandler) => {
|
||||
if (bodySchema) {
|
||||
const parsed = bodySchema.safeParse(JSON.parse(JSON.stringify(req.body)));
|
||||
if (!parsed.success) {
|
||||
@@ -42,8 +40,8 @@ const validateRequest =
|
||||
}
|
||||
req.query = parsed.data;
|
||||
}
|
||||
|
||||
return next();
|
||||
};
|
||||
};
|
||||
|
||||
export default validateRequest;
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import BreweryPostMapQueryResult from '@/services/BreweryPost/types/BreweryPostMapQueryResult';
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
import useSWRInfinite from 'swr/infinite';
|
||||
import { z } from 'zod';
|
||||
|
||||
const useBreweryMapPagePosts = ({ pageSize }: { pageSize: number }) => {
|
||||
const fetcher = async (url: string) => {
|
||||
const response = await fetch(url);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(response.statusText);
|
||||
}
|
||||
|
||||
const json = await response.json();
|
||||
|
||||
const count = response.headers.get('X-Total-Count');
|
||||
|
||||
const parsed = APIResponseValidationSchema.safeParse(json);
|
||||
if (!parsed.success) {
|
||||
throw new Error('API response validation failed');
|
||||
}
|
||||
|
||||
const parsedPayload = z
|
||||
.array(BreweryPostMapQueryResult)
|
||||
.safeParse(parsed.data.payload);
|
||||
if (!parsedPayload.success) {
|
||||
throw new Error('API payload validation failed');
|
||||
}
|
||||
|
||||
const pageCount = Math.ceil((count as string, 10) / pageSize);
|
||||
|
||||
return { breweryPosts: parsedPayload.data, pageCount };
|
||||
};
|
||||
|
||||
const { data, error, isLoading, setSize, size } = useSWRInfinite(
|
||||
(index) => `/api/breweries/map?page_num=${index + 1}&page_size=${pageSize}`,
|
||||
fetcher,
|
||||
);
|
||||
|
||||
const breweryPosts = data?.flatMap((d) => d.breweryPosts) ?? [];
|
||||
const pageCount = data?.[0].pageCount ?? 0;
|
||||
|
||||
const isLoadingMore = size > 0 && data && typeof data[size - 1] === 'undefined';
|
||||
const isAtEnd = !(size < data?.[0].pageCount!);
|
||||
|
||||
return {
|
||||
breweries: breweryPosts,
|
||||
isLoading,
|
||||
isLoadingMore,
|
||||
isAtEnd,
|
||||
size,
|
||||
setSize,
|
||||
pageCount,
|
||||
error: error as unknown,
|
||||
};
|
||||
};
|
||||
|
||||
export default useBreweryMapPagePosts;
|
||||
@@ -1,13 +1,193 @@
|
||||
import withPageAuthRequired from '@/util/withPageAuthRequired';
|
||||
import { NextPage } from 'next';
|
||||
|
||||
interface AccountPageProps {}
|
||||
import { FC, useState } from 'react';
|
||||
import { Switch, Tab } from '@headlessui/react';
|
||||
import Head from 'next/head';
|
||||
import FormInfo from '@/components/ui/forms/FormInfo';
|
||||
import FormLabel from '@/components/ui/forms/FormLabel';
|
||||
import FormError from '@/components/ui/forms/FormError';
|
||||
import FormTextInput from '@/components/ui/forms/FormTextInput';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import GetUserSchema from '@/services/User/schema/GetUserSchema';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
|
||||
interface AccountPageProps {
|
||||
user: z.infer<typeof GetUserSchema>;
|
||||
}
|
||||
|
||||
const AccountInfo: FC<{
|
||||
user: z.infer<typeof GetUserSchema>;
|
||||
}> = ({ user }) => {
|
||||
const { register, handleSubmit, formState, reset } = useForm<
|
||||
z.infer<typeof GetUserSchema>
|
||||
>({
|
||||
resolver: zodResolver(GetUserSchema),
|
||||
defaultValues: {
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
dateOfBirth: user.dateOfBirth,
|
||||
},
|
||||
});
|
||||
|
||||
const [inEditMode, setInEditMode] = useState(false);
|
||||
|
||||
const AccountPage: NextPage<AccountPageProps> = () => {
|
||||
return (
|
||||
<div className="mt-8">
|
||||
<div className="flex flex-col space-y-3">
|
||||
<div className="flex flex-row">
|
||||
<label className="label-text" htmlFor="edit-toggle">
|
||||
Edit Account Info
|
||||
</label>
|
||||
<Switch
|
||||
checked={inEditMode}
|
||||
className="toggle"
|
||||
onClick={() => {
|
||||
setInEditMode((editMode) => !editMode);
|
||||
reset();
|
||||
}}
|
||||
id="edit-toggle"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<form className="space-y-5" onSubmit={handleSubmit(() => {})}>
|
||||
<div>
|
||||
<h1>Account Page</h1>
|
||||
<FormInfo>
|
||||
<FormLabel htmlFor="username">Username</FormLabel>
|
||||
<FormError>{formState.errors.username?.message}</FormError>
|
||||
</FormInfo>
|
||||
<FormTextInput
|
||||
type="text"
|
||||
disabled={!inEditMode || formState.isSubmitting}
|
||||
error={!!formState.errors.username}
|
||||
id="username"
|
||||
formValidationSchema={register('username')}
|
||||
/>
|
||||
<FormInfo>
|
||||
<FormLabel htmlFor="email">Email</FormLabel>
|
||||
<FormError>{''}</FormError>
|
||||
</FormInfo>
|
||||
<FormTextInput
|
||||
type="email"
|
||||
disabled={!inEditMode || formState.isSubmitting}
|
||||
error={!!formState.errors.email}
|
||||
id="email"
|
||||
formValidationSchema={register('email')}
|
||||
/>
|
||||
|
||||
<div className="flex space-x-3">
|
||||
<div className="w-1/2">
|
||||
<FormInfo>
|
||||
<FormLabel htmlFor="firstName">First Name</FormLabel>
|
||||
<FormError>{formState.errors.firstName?.message}</FormError>
|
||||
</FormInfo>
|
||||
<FormTextInput
|
||||
type="text"
|
||||
disabled={!inEditMode || formState.isSubmitting}
|
||||
error={!!formState.errors.firstName}
|
||||
id="firstName"
|
||||
formValidationSchema={register('firstName')}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-1/2">
|
||||
<FormInfo>
|
||||
<FormLabel htmlFor="lastName">Last Name</FormLabel>
|
||||
<FormError>{formState.errors.lastName?.message}</FormError>
|
||||
</FormInfo>
|
||||
<FormTextInput
|
||||
type="text"
|
||||
disabled={!inEditMode || formState.isSubmitting}
|
||||
error={!!formState.errors.lastName}
|
||||
id="lastName"
|
||||
formValidationSchema={register('lastName')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{inEditMode && <button className="btn-primary btn w-full">Save Changes</button>}
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const AccountPage: NextPage<AccountPageProps> = ({ user }) => {
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>Your Account | The Biergarten App</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="Your account page. Here you can view your account information, change your settings, and view your posts."
|
||||
/>
|
||||
</Head>
|
||||
<div className="flex h-full flex-col items-center bg-base-300">
|
||||
<div className="m-12 flex w-9/12 flex-col items-center justify-center space-y-3">
|
||||
<div className="flex flex-col items-center space-y-3">
|
||||
<div className="avatar">
|
||||
<div className="bg-base-black w-24 rounded-full bg-slate-700" />
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-center space-y-1">
|
||||
<p className="text-3xl font-bold">Hello, {user.username}!</p>
|
||||
<p className="text-lg">Welcome to your account page.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="w-full">
|
||||
<Tab.Group>
|
||||
<Tab.List className="tabs tabs-boxed items-center justify-center rounded-2xl">
|
||||
<Tab className="tab tab-md w-1/2 uppercase ui-selected:tab-active">
|
||||
Account Info
|
||||
</Tab>
|
||||
<Tab className="tab tab-md w-1/2 uppercase ui-selected:tab-active">
|
||||
Your Posts
|
||||
</Tab>
|
||||
</Tab.List>
|
||||
<Tab.Panels>
|
||||
<Tab.Panel>
|
||||
<AccountInfo user={user} />
|
||||
</Tab.Panel>
|
||||
<Tab.Panel>Content 3</Tab.Panel>
|
||||
</Tab.Panels>
|
||||
</Tab.Group>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default AccountPage;
|
||||
|
||||
export const getServerSideProps = withPageAuthRequired(async (context, session) => {
|
||||
const { id } = session;
|
||||
|
||||
const user: z.infer<typeof GetUserSchema> | null =
|
||||
await DBClient.instance.user.findUnique({
|
||||
where: { id },
|
||||
select: {
|
||||
username: true,
|
||||
email: true,
|
||||
accountIsVerified: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
dateOfBirth: true,
|
||||
id: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return { redirect: { destination: '/login', permanent: false } };
|
||||
}
|
||||
return {
|
||||
props: {
|
||||
user: JSON.parse(JSON.stringify(user)),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
68
src/pages/api/breweries/map/index.ts
Normal file
68
src/pages/api/breweries/map/index.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import BreweryPostMapQueryResult from '@/services/BreweryPost/types/BreweryPostMapQueryResult';
|
||||
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
import { NextApiRequest, NextApiResponse } from 'next';
|
||||
import { createRouter } from 'next-connect';
|
||||
import { z } from 'zod';
|
||||
|
||||
interface GetBreweryPostsRequest extends NextApiRequest {
|
||||
query: {
|
||||
page_num: string;
|
||||
page_size: string;
|
||||
};
|
||||
}
|
||||
|
||||
const getBreweryPosts = async (
|
||||
req: GetBreweryPostsRequest,
|
||||
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
|
||||
) => {
|
||||
const pageNum = parseInt(req.query.page_num, 10);
|
||||
const pageSize = parseInt(req.query.page_size, 10);
|
||||
|
||||
const skip = (pageNum - 1) * pageSize;
|
||||
const take = pageSize;
|
||||
|
||||
const breweryPosts: z.infer<typeof BreweryPostMapQueryResult>[] =
|
||||
await DBClient.instance.breweryPost.findMany({
|
||||
select: {
|
||||
location: {
|
||||
select: { coordinates: true, city: true, country: true, stateOrProvince: true },
|
||||
},
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
skip,
|
||||
take,
|
||||
});
|
||||
const breweryPostCount = await DBClient.instance.breweryPost.count();
|
||||
|
||||
res.setHeader('X-Total-Count', breweryPostCount);
|
||||
|
||||
res.status(200).json({
|
||||
message: 'Brewery posts retrieved successfully',
|
||||
statusCode: 200,
|
||||
payload: breweryPosts,
|
||||
success: true,
|
||||
});
|
||||
};
|
||||
|
||||
const router = createRouter<
|
||||
GetBreweryPostsRequest,
|
||||
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
|
||||
>();
|
||||
|
||||
router.get(
|
||||
validateRequest({
|
||||
querySchema: z.object({
|
||||
page_num: z.string().regex(/^\d+$/),
|
||||
page_size: z.string().regex(/^\d+$/),
|
||||
}),
|
||||
}),
|
||||
getBreweryPosts,
|
||||
);
|
||||
|
||||
const handler = router.handler();
|
||||
|
||||
export default handler;
|
||||
43
src/pages/api/users/check-email.ts
Normal file
43
src/pages/api/users/check-email.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
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 validateRequest from '@/config/nextConnect/middleware/validateRequest';
|
||||
import findUserByEmail from '@/services/User/findUserByEmail';
|
||||
|
||||
const CheckEmailRequestQuerySchema = z.object({
|
||||
email: z.string(),
|
||||
});
|
||||
|
||||
interface CheckEmailRequestSchema extends NextApiRequest {
|
||||
query: z.infer<typeof CheckEmailRequestQuerySchema>;
|
||||
}
|
||||
|
||||
const router = createRouter<
|
||||
CheckEmailRequestSchema,
|
||||
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
|
||||
>();
|
||||
|
||||
const checkEmail = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
const { email: emailToCheck } = req.query;
|
||||
|
||||
const email = await findUserByEmail(emailToCheck as string);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
payload: { emailIsTaken: !!email },
|
||||
statusCode: 200,
|
||||
message: 'Getting username availability.',
|
||||
});
|
||||
};
|
||||
|
||||
router.get(
|
||||
validateRequest({ querySchema: z.object({ email: z.string().email() }) }),
|
||||
checkEmail,
|
||||
);
|
||||
|
||||
const handler = router.handler(NextConnectOptions);
|
||||
|
||||
export default handler;
|
||||
43
src/pages/api/users/check-username.ts
Normal file
43
src/pages/api/users/check-username.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
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 validateRequest from '@/config/nextConnect/middleware/validateRequest';
|
||||
import findUserByUsername from '@/services/User/findUserByUsername';
|
||||
|
||||
const CheckUsernameRequestQuerySchema = z.object({
|
||||
username: z.string(),
|
||||
});
|
||||
|
||||
interface CheckUsernameRequestSchema extends NextApiRequest {
|
||||
query: z.infer<typeof CheckUsernameRequestQuerySchema>;
|
||||
}
|
||||
|
||||
const router = createRouter<
|
||||
CheckUsernameRequestSchema,
|
||||
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
|
||||
>();
|
||||
|
||||
const checkUsername = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
const { username: usernameToCheck } = req.query;
|
||||
|
||||
const user = await findUserByUsername(usernameToCheck as string);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
payload: { usernameIsTaken: !!user },
|
||||
statusCode: 200,
|
||||
message: 'Getting username availability.',
|
||||
});
|
||||
};
|
||||
|
||||
router.get(
|
||||
validateRequest({ querySchema: z.object({ username: z.string() }) }),
|
||||
checkUsername,
|
||||
);
|
||||
|
||||
const handler = router.handler(NextConnectOptions);
|
||||
|
||||
export default handler;
|
||||
@@ -27,7 +27,7 @@ const confirmUser = async (req: ConfirmUserRequest, res: NextApiResponse) => {
|
||||
throw new ServerError('Could not confirm user.', 401);
|
||||
}
|
||||
|
||||
if (user.isAccountVerified) {
|
||||
if (user.accountIsVerified) {
|
||||
throw new ServerError('User is already verified.', 400);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,46 +1,31 @@
|
||||
import { GetServerSideProps, NextPage } from 'next';
|
||||
import { useMemo, useState } from 'react';
|
||||
import Map, {
|
||||
FullscreenControl,
|
||||
Marker,
|
||||
NavigationControl,
|
||||
Popup,
|
||||
ScaleControl,
|
||||
} from 'react-map-gl';
|
||||
import { NextPage } from 'next';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import Map, { Marker, Popup } from 'react-map-gl';
|
||||
import 'mapbox-gl/dist/mapbox-gl.css';
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
|
||||
import LocationMarker from '@/components/ui/LocationMarker';
|
||||
import Link from 'next/link';
|
||||
import Head from 'next/head';
|
||||
import useGeolocation from '@/hooks/utilities/useGeolocation';
|
||||
import BreweryPostMapQueryResult from '@/services/BreweryPost/types/BreweryPostMapQueryResult';
|
||||
import { z } from 'zod';
|
||||
import useBreweryMapPagePosts from '@/hooks/data-fetching/brewery-posts/useBreweryMapPagePosts';
|
||||
import ControlPanel from '@/components/ui/maps/ControlPanel';
|
||||
|
||||
type MapStyles = Record<'light' | 'dark', `mapbox://styles/mapbox/${string}`>;
|
||||
|
||||
interface BreweryMapPageProps {
|
||||
breweries: {
|
||||
location: {
|
||||
city: string;
|
||||
stateOrProvince: string | null;
|
||||
country: string | null;
|
||||
coordinates: number[];
|
||||
};
|
||||
id: string;
|
||||
name: string;
|
||||
}[];
|
||||
}
|
||||
const BreweryMapPage: NextPage = () => {
|
||||
const [popupInfo, setPopupInfo] = useState<z.infer<
|
||||
typeof BreweryPostMapQueryResult
|
||||
> | null>(null);
|
||||
|
||||
const BreweryMapPage: NextPage<BreweryMapPageProps> = ({ breweries }) => {
|
||||
const windowIsDefined = typeof window !== 'undefined';
|
||||
const themeIsDefined = windowIsDefined && !!window.localStorage.getItem('theme');
|
||||
const [theme, setTheme] = useState<'light' | 'dark'>('light');
|
||||
|
||||
const [popupInfo, setPopupInfo] = useState<BreweryMapPageProps['breweries'][0] | null>(
|
||||
null,
|
||||
);
|
||||
useEffect(() => {
|
||||
setTheme(localStorage.getItem('theme') === 'dark' ? 'dark' : 'light');
|
||||
}, []);
|
||||
|
||||
const theme = (
|
||||
windowIsDefined && themeIsDefined ? window.localStorage.getItem('theme') : 'light'
|
||||
) as 'light' | 'dark';
|
||||
const { breweries } = useBreweryMapPagePosts({ pageSize: 50 });
|
||||
|
||||
const mapStyles: MapStyles = {
|
||||
light: 'mapbox://styles/mapbox/light-v10',
|
||||
@@ -52,11 +37,12 @@ const BreweryMapPage: NextPage<BreweryMapPageProps> = ({ breweries }) => {
|
||||
<>
|
||||
{breweries.map((brewery) => {
|
||||
const [longitude, latitude] = brewery.location.coordinates;
|
||||
|
||||
return (
|
||||
<Marker
|
||||
key={brewery.id}
|
||||
latitude={latitude}
|
||||
longitude={longitude}
|
||||
key={brewery.id}
|
||||
onClick={(e) => {
|
||||
e.originalEvent.stopPropagation();
|
||||
setPopupInfo(brewery);
|
||||
@@ -71,16 +57,16 @@ const BreweryMapPage: NextPage<BreweryMapPageProps> = ({ breweries }) => {
|
||||
[breweries],
|
||||
);
|
||||
|
||||
const { coords, error } = useGeolocation();
|
||||
const { coords, error: geoError } = useGeolocation();
|
||||
|
||||
const userLocationPin = useMemo(
|
||||
() =>
|
||||
coords && !error ? (
|
||||
coords && !geoError ? (
|
||||
<Marker latitude={coords.latitude} longitude={coords.longitude}>
|
||||
<LocationMarker size="lg" color="red" />
|
||||
</Marker>
|
||||
) : null,
|
||||
[coords, error],
|
||||
[coords, geoError],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -94,15 +80,14 @@ const BreweryMapPage: NextPage<BreweryMapPageProps> = ({ breweries }) => {
|
||||
</Head>
|
||||
<div className="h-full">
|
||||
<Map
|
||||
initialViewState={{ zoom: 2 }}
|
||||
// center the map on North America
|
||||
initialViewState={{ zoom: 3, latitude: 48.3544, longitude: -99.9981 }}
|
||||
style={{ width: '100%', height: '100%' }}
|
||||
mapStyle={mapStyles[theme]}
|
||||
mapboxAccessToken={process.env.NEXT_PUBLIC_MAPBOX_ACCESS_TOKEN}
|
||||
scrollZoom
|
||||
>
|
||||
<FullscreenControl position="top-left" />
|
||||
<NavigationControl position="top-left" />
|
||||
<ScaleControl />
|
||||
<ControlPanel />
|
||||
{pins}
|
||||
{userLocationPin}
|
||||
{popupInfo && (
|
||||
@@ -136,17 +121,3 @@ const BreweryMapPage: NextPage<BreweryMapPageProps> = ({ breweries }) => {
|
||||
};
|
||||
|
||||
export default BreweryMapPage;
|
||||
|
||||
export const getServerSideProps: GetServerSideProps<BreweryMapPageProps> = async () => {
|
||||
const breweries = await DBClient.instance.breweryPost.findMany({
|
||||
select: {
|
||||
location: {
|
||||
select: { coordinates: true, city: true, country: true, stateOrProvince: true },
|
||||
},
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
});
|
||||
|
||||
return { props: { breweries } };
|
||||
};
|
||||
|
||||
9
src/prisma/migrations/20230510010306_/migration.sql
Normal file
9
src/prisma/migrations/20230510010306_/migration.sql
Normal file
@@ -0,0 +1,9 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- You are about to drop the column `isAccountVerified` on the `User` table. All the data in the column will be lost.
|
||||
|
||||
*/
|
||||
-- AlterTable
|
||||
ALTER TABLE "User" DROP COLUMN "isAccountVerified",
|
||||
ADD COLUMN "accountIsVerified" BOOLEAN NOT NULL DEFAULT false;
|
||||
@@ -21,7 +21,7 @@ model User {
|
||||
email String @unique
|
||||
createdAt DateTime @default(now()) @db.Timestamptz(3)
|
||||
updatedAt DateTime? @updatedAt @db.Timestamptz(3)
|
||||
isAccountVerified Boolean @default(false)
|
||||
accountIsVerified Boolean @default(false)
|
||||
dateOfBirth DateTime
|
||||
beerPosts BeerPost[]
|
||||
beerTypes BeerType[]
|
||||
|
||||
@@ -53,7 +53,16 @@ const createNewUsers = async ({ numberOfUsers }: CreateNewUsersArgs) => {
|
||||
const dateOfBirth = faker.date.birthdate({ mode: 'age', min: 19 });
|
||||
const createdAt = faker.date.past(1);
|
||||
|
||||
const user = { firstName, lastName, email, username, dateOfBirth, createdAt, hash };
|
||||
const user = {
|
||||
firstName,
|
||||
lastName,
|
||||
email,
|
||||
username,
|
||||
dateOfBirth,
|
||||
createdAt,
|
||||
hash,
|
||||
accountIsVerified: true,
|
||||
};
|
||||
|
||||
data.push(user);
|
||||
}
|
||||
|
||||
25
src/requests/valdiateEmail.ts
Normal file
25
src/requests/valdiateEmail.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
import { z } from 'zod';
|
||||
|
||||
const validateEmail = async (email: string) => {
|
||||
const response = await fetch(`/api/users/check-email?email=${email}`);
|
||||
const json = await response.json();
|
||||
|
||||
const parsed = APIResponseValidationSchema.safeParse(json);
|
||||
|
||||
if (!parsed.success) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const parsedPayload = z
|
||||
.object({ usernameIsTaken: z.boolean() })
|
||||
.safeParse(parsed.data.payload);
|
||||
|
||||
if (!parsedPayload.success) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !parsedPayload.data.usernameIsTaken;
|
||||
};
|
||||
|
||||
export default validateEmail;
|
||||
25
src/requests/validateUsername.ts
Normal file
25
src/requests/validateUsername.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
import { z } from 'zod';
|
||||
|
||||
const validateUsername = async (username: string) => {
|
||||
const response = await fetch(`/api/users/check-username?username=${username}`);
|
||||
const json = await response.json();
|
||||
|
||||
const parsed = APIResponseValidationSchema.safeParse(json);
|
||||
|
||||
if (!parsed.success) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const parsedPayload = z
|
||||
.object({ usernameIsTaken: z.boolean() })
|
||||
.safeParse(parsed.data.payload);
|
||||
|
||||
if (!parsedPayload.success) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !parsedPayload.data.usernameIsTaken;
|
||||
};
|
||||
|
||||
export default validateUsername;
|
||||
14
src/services/BreweryPost/types/BreweryPostMapQueryResult.ts
Normal file
14
src/services/BreweryPost/types/BreweryPostMapQueryResult.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const BreweryPostMapQueryResult = z.object({
|
||||
location: z.object({
|
||||
coordinates: z.array(z.number()),
|
||||
city: z.string(),
|
||||
country: z.string().nullable(),
|
||||
stateOrProvince: z.string().nullable(),
|
||||
}),
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
});
|
||||
|
||||
export default BreweryPostMapQueryResult;
|
||||
@@ -30,7 +30,7 @@ const createNewUser = async ({
|
||||
lastName: true,
|
||||
dateOfBirth: true,
|
||||
createdAt: true,
|
||||
isAccountVerified: true,
|
||||
accountIsVerified: true,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ const findUserById = async (id: string) => {
|
||||
lastName: true,
|
||||
dateOfBirth: true,
|
||||
createdAt: true,
|
||||
isAccountVerified: true,
|
||||
accountIsVerified: true,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import validateEmail from '@/requests/valdiateEmail';
|
||||
import validateUsername from '@/requests/validateUsername';
|
||||
import sub from 'date-fns/sub';
|
||||
import { z } from 'zod';
|
||||
|
||||
const minimumDateOfBirth = sub(new Date(), { years: 19 });
|
||||
const CreateUserValidationSchema = z
|
||||
.object({
|
||||
email: z.string().email({ message: 'Email must be a valid email address.' }),
|
||||
const CreateUserValidationSchema = z.object({
|
||||
// use special characters, numbers, and uppercase letters
|
||||
password: z
|
||||
.string()
|
||||
@@ -33,10 +33,6 @@ const CreateUserValidationSchema = z
|
||||
.refine((lastName) => /^[a-zA-Z]+$/.test(lastName), {
|
||||
message: 'Last name must only contain letters.',
|
||||
}),
|
||||
username: z
|
||||
.string()
|
||||
.min(1, { message: 'Username must not be empty.' })
|
||||
.max(20, { message: 'Username must be less than 20 characters.' }),
|
||||
dateOfBirth: z.string().refine(
|
||||
(dateOfBirth) => {
|
||||
const parsedDateOfBirth = new Date(dateOfBirth);
|
||||
@@ -44,10 +40,36 @@ const CreateUserValidationSchema = z
|
||||
},
|
||||
{ message: 'You must be at least 19 years old to register.' },
|
||||
),
|
||||
})
|
||||
.refine((data) => data.password === data.confirmPassword, {
|
||||
});
|
||||
|
||||
export default CreateUserValidationSchema.extend({
|
||||
username: z
|
||||
.string()
|
||||
.min(1, { message: 'Username must not be empty.' })
|
||||
.max(20, { message: 'Username must be less than 20 characters.' }),
|
||||
|
||||
email: z.string().email({ message: 'Email must be a valid email address.' }),
|
||||
}).refine((data) => data.password === data.confirmPassword, {
|
||||
message: 'Passwords do not match.',
|
||||
path: ['confirmPassword'],
|
||||
});
|
||||
|
||||
export default CreateUserValidationSchema;
|
||||
export const CreateUserValidationSchemaWithUsernameAndEmailCheck =
|
||||
CreateUserValidationSchema.extend({
|
||||
email: z
|
||||
.string()
|
||||
.email({ message: 'Email must be a valid email address.' })
|
||||
.refine(async (email) => validateEmail(email), {
|
||||
message: 'Email is already taken.',
|
||||
}),
|
||||
username: z
|
||||
.string()
|
||||
.min(1, { message: 'Username must not be empty.' })
|
||||
.max(20, { message: 'Username must be less than 20 characters.' })
|
||||
.refine(async (username) => validateUsername(username), {
|
||||
message: 'Username is already taken.',
|
||||
}),
|
||||
}).refine((data) => data.password === data.confirmPassword, {
|
||||
message: 'Passwords do not match.',
|
||||
path: ['confirmPassword'],
|
||||
});
|
||||
|
||||
@@ -9,7 +9,7 @@ const GetUserSchema = z.object({
|
||||
firstName: z.string(),
|
||||
lastName: z.string(),
|
||||
dateOfBirth: z.coerce.date(),
|
||||
isAccountVerified: z.boolean(),
|
||||
accountIsVerified: z.boolean(),
|
||||
});
|
||||
|
||||
export default GetUserSchema;
|
||||
|
||||
@@ -5,12 +5,12 @@ import { z } from 'zod';
|
||||
const updateUserToBeConfirmedById = async (id: string) => {
|
||||
const user: z.infer<typeof GetUserSchema> = await DBClient.instance.user.update({
|
||||
where: { id },
|
||||
data: { isAccountVerified: true, updatedAt: new Date() },
|
||||
data: { accountIsVerified: true, updatedAt: new Date() },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
email: true,
|
||||
isAccountVerified: true,
|
||||
accountIsVerified: true,
|
||||
createdAt: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
|
||||
Reference in New Issue
Block a user