Refactor: update beer style, brewery post services

This commit is contained in:
Aaron William Po
2023-12-14 22:18:59 -05:00
parent 0de4697e77
commit 70a168df92
26 changed files with 671 additions and 633 deletions

View File

@@ -1,81 +1,17 @@
import getCurrentUser from '@/config/nextConnect/middleware/getCurrentUser';
import { UserExtendedNextApiRequest } from '@/config/auth/types';
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiResponse } from 'next';
import { createRouter, NextHandler } from 'next-connect';
import { createRouter } from 'next-connect';
import { z } from 'zod';
import ServerError from '@/config/util/ServerError';
import DBClient from '@/prisma/DBClient';
import getBreweryPostById from '@/services/posts/brewery-post/getBreweryPostById';
import EditBreweryPostValidationSchema from '@/services/posts/brewery-post/schema/EditBreweryPostValidationSchema';
interface BreweryPostRequest extends UserExtendedNextApiRequest {
query: { id: string };
}
import {
checkIfBreweryPostOwner,
editBreweryPost,
deleteBreweryPost,
} from '@/controllers/posts/breweries';
import { EditBreweryPostRequest } from '@/controllers/posts/breweries/types';
interface EditBreweryPostRequest extends BreweryPostRequest {
body: z.infer<typeof EditBreweryPostValidationSchema>;
}
const checkIfBreweryPostOwner = async (
req: BreweryPostRequest,
res: NextApiResponse,
next: NextHandler,
) => {
const user = req.user!;
const { id } = req.query;
const breweryPost = await getBreweryPostById(id);
if (!breweryPost) {
throw new ServerError('Brewery post not found', 404);
}
if (breweryPost.postedBy.id !== user.id) {
throw new ServerError('You are not the owner of this brewery post', 403);
}
return next();
};
const editBreweryPost = async (
req: EditBreweryPostRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const {
body,
query: { id },
} = req;
await DBClient.instance.breweryPost.update({
where: { id },
data: body,
});
res.status(200).json({
message: 'Brewery post updated successfully',
success: true,
statusCode: 200,
});
};
const deleteBreweryPost = async (req: BreweryPostRequest, res: NextApiResponse) => {
const {
query: { id },
} = req;
const deleted = await DBClient.instance.breweryPost.delete({ where: { id } });
if (!deleted) {
throw new ServerError('Brewery post not found', 404);
}
res.status(200).json({
message: 'Brewery post deleted successfully',
success: true,
statusCode: 200,
});
};
const router = createRouter<
EditBreweryPostRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>

View File

@@ -6,56 +6,9 @@ import { z } from 'zod';
import NextConnectOptions from '@/config/nextConnect/NextConnectOptions';
import getCurrentUser from '@/config/nextConnect/middleware/getCurrentUser';
import CreateBreweryPostSchema from '@/services/posts/brewery-post/schema/CreateBreweryPostSchema';
import createNewBreweryPost from '@/services/posts/brewery-post/createNewBreweryPost';
import geocode from '@/config/mapbox/geocoder';
import ServerError from '@/config/util/ServerError';
import DBClient from '@/prisma/DBClient';
import { CreateBreweryPostRequest } from '@/controllers/posts/breweries/types';
const createBreweryPost = async (
req: CreateBreweryPostRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const { name, description, dateEstablished, address, city, country, region } = req.body;
const userId = req.user!.id;
const fullAddress = `${address}, ${city}, ${region}, ${country}`;
const geocoded = await geocode(fullAddress);
if (!geocoded) {
throw new ServerError('Address is not valid', 400);
}
const [latitude, longitude] = geocoded.center;
const location = await DBClient.instance.breweryLocation.create({
data: {
address,
city,
country,
stateOrProvince: region,
coordinates: [latitude, longitude],
postedBy: { connect: { id: userId } },
},
select: { id: true },
});
const newBreweryPost = await createNewBreweryPost({
name,
description,
locationId: location.id,
dateEstablished,
userId,
});
res.status(201).json({
message: 'Brewery post created successfully',
statusCode: 201,
payload: newBreweryPost,
success: true,
});
};
import { createBreweryPost } from '@/controllers/posts/breweries';
const router = createRouter<
CreateBreweryPostRequest,

View File

@@ -1,51 +1,15 @@
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
import DBClient from '@/prisma/DBClient';
import BreweryPostMapQueryResult from '@/services/posts/brewery-post/schema/BreweryPostMapQueryResult';
import { getMapBreweryPosts } from '@/controllers/posts/breweries';
import { GetBreweryPostsRequest } from '@/controllers/posts/breweries/types';
import PaginatedQueryResponseSchema from '@/services/schema/PaginatedQueryResponseSchema';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiRequest, NextApiResponse } from 'next';
import { NextApiResponse } from 'next';
import { createRouter } from 'next-connect';
import { z } from 'zod';
interface GetBreweryPostsRequest extends NextApiRequest {
query: z.infer<typeof PaginatedQueryResponseSchema>;
}
const getMapBreweryPosts = 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>>

View File

@@ -5,11 +5,12 @@ import { z } from 'zod';
import useMediaQuery from '@/hooks/utilities/useMediaQuery';
import { Tab } from '@headlessui/react';
import getBeerStyleById from '@/services/posts/beer-style-post/getBeerStyleById';
import BeerStyleHeader from '@/components/BeerStyleById/BeerStyleHeader';
import BeerStyleQueryResult from '@/services/posts/beer-style-post/schema/BeerStyleQueryResult';
import BeerStyleCommentSection from '@/components/BeerStyleById/BeerStyleCommentSection';
import BeerStyleBeerSection from '@/components/BeerStyleById/BeerStyleBeerSection';
import { getBeerStyleByIdService } from '@/services/posts/beer-style-post';
interface BeerStylePageProps {
beerStyle: z.infer<typeof BeerStyleQueryResult>;
@@ -69,7 +70,7 @@ export default BeerStyleByIdPage;
export const getServerSideProps: GetServerSideProps = async ({ params }) => {
const id = params!.id as string;
const beerStyle = await getBeerStyleById(id);
const beerStyle = await getBeerStyleByIdService({ beerStyleId: id });
if (!beerStyle) {
return { notFound: true };
}

View File

@@ -8,7 +8,7 @@ import { BeerStyle } from '@prisma/client';
import { NextPage } from 'next';
import { BiBeer } from 'react-icons/bi';
import { z } from 'zod';
import getBreweryPostById from '@/services/posts/brewery-post/getBreweryPostById';
import { getBreweryPostByIdService } from '@/services/posts/brewery-post';
interface CreateBeerPageProps {
brewery: z.infer<typeof BreweryPostQueryResult>;
@@ -32,7 +32,7 @@ export const getServerSideProps = withPageAuthRequired<CreateBeerPageProps>(
async (context) => {
const id = context.params?.id as string;
const breweryPost = await getBreweryPostById(id);
const breweryPost = await getBreweryPostByIdService({ breweryPostId: id });
const beerStyles = await DBClient.instance.beerStyle.findMany();
return {

View File

@@ -5,7 +5,8 @@ import FormPageLayout from '@/components/ui/forms/FormPageLayout';
import FormSegment from '@/components/ui/forms/FormSegment';
import FormTextArea from '@/components/ui/forms/FormTextArea';
import FormTextInput from '@/components/ui/forms/FormTextInput';
import getBreweryPostById from '@/services/posts/brewery-post/getBreweryPostById';
import { getBreweryPostByIdService } from '@/services/posts/brewery-post';
import BreweryPostQueryResult from '@/services/posts/brewery-post/schema/BreweryPostQueryResult';
import EditBreweryPostValidationSchema from '@/services/posts/brewery-post/schema/EditBreweryPostValidationSchema';
import withPageAuthRequired from '@/util/withPageAuthRequired';
@@ -143,7 +144,7 @@ export default EditBreweryPostPage;
export const getServerSideProps = withPageAuthRequired<EditPageProps>(
async (context, session) => {
const breweryPostId = context.params?.id as string;
const breweryPost = await getBreweryPostById(breweryPostId);
const breweryPost = await getBreweryPostByIdService({ breweryPostId });
const { id: userId } = session;

View File

@@ -1,4 +1,3 @@
import getBreweryPostById from '@/services/posts/brewery-post/getBreweryPostById';
import BreweryPostQueryResult from '@/services/posts/brewery-post/schema/BreweryPostQueryResult';
import { GetServerSideProps, NextPage } from 'next';
@@ -13,6 +12,7 @@ import { Tab } from '@headlessui/react';
import dynamic from 'next/dynamic';
import { MAPBOX_ACCESS_TOKEN } from '@/config/env';
import { CldImage } from 'next-cloudinary';
import { getBreweryPostByIdService } from '@/services/posts/brewery-post';
const [BreweryInfoHeader, BreweryBeersSection, BreweryCommentsSection, BreweryPostMap] = [
dynamic(() => import('@/components/BreweryById/BreweryInfoHeader')),
@@ -114,7 +114,9 @@ const BreweryByIdPage: NextPage<BreweryPageProps> = ({ breweryPost, mapboxToken
export const getServerSideProps: GetServerSideProps<BreweryPageProps> = async (
context,
) => {
const breweryPost = await getBreweryPostById(context.params!.id! as string);
const breweryPost = await getBreweryPostByIdService({
breweryPostId: context.params?.id as string,
});
const mapboxToken = MAPBOX_ACCESS_TOKEN;
return !breweryPost