Update api routes and begin to extract controllers out of routing logic

This commit is contained in:
Aaron William Po
2023-12-03 11:51:54 -05:00
parent 080eb4c3c3
commit b45ed857d3
16 changed files with 345 additions and 408 deletions

View File

@@ -29,7 +29,7 @@ import FormTextInput from '../ui/forms/FormTextInput';
import Button from '../ui/forms/Button';
const AddressAutofill = dynamic(
// @ts-ignore
// @ts-expect-error
() => import('@mapbox/search-js-react').then((mod) => mod.AddressAutofill),
{ ssr: false },
);

View File

@@ -0,0 +1,66 @@
import ServerError from '@/config/util/ServerError';
import DBClient from '@/prisma/DBClient';
import editBeerCommentById from '@/services/BeerComment/editBeerCommentById';
import findBeerCommentById from '@/services/BeerComment/findBeerCommentById';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiResponse } from 'next';
import { NextHandler } from 'next-connect';
import { z } from 'zod';
import { CommentRequest, EditCommentRequest } from '../requestTypes';
export const checkIfBeerCommentOwner = async <T extends CommentRequest>(
req: T,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
next: NextHandler,
) => {
const { id } = req.query;
const user = req.user!;
const comment = await findBeerCommentById({ beerCommentId: id });
if (!comment) {
throw new ServerError('Comment not found', 404);
}
if (comment.postedBy.id !== user.id) {
throw new ServerError('You are not authorized to modify this comment', 403);
}
return next();
};
export const editBeerPostComment = async (
req: EditCommentRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const { id } = req.query;
const updated = await editBeerCommentById({
content: req.body.content,
rating: req.body.rating,
id,
});
res.status(200).json({
success: true,
message: 'Comment updated successfully',
statusCode: 200,
payload: updated,
});
};
export const deleteBeerPostComment = async (
req: CommentRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const { id } = req.query;
await DBClient.instance.beerComment.delete({
where: { id },
});
res.status(200).json({
success: true,
message: 'Comment deleted successfully',
statusCode: 200,
});
};

View File

@@ -0,0 +1,67 @@
import ServerError from '@/config/util/ServerError';
import DBClient from '@/prisma/DBClient';
import updateBeerStyleCommentById from '@/services/BeerStyleComment/updateBeerStyleCommentById';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiResponse } from 'next';
import { NextHandler } from 'next-connect';
import { z } from 'zod';
import { CommentRequest, EditCommentRequest } from '../requestTypes';
export const checkIfBeerStyleCommentOwner = async <
CommentRequestType extends CommentRequest,
>(
req: CommentRequestType,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
next: NextHandler,
) => {
const { id } = req.query;
const user = req.user!;
const beerStyleComment = await DBClient.instance.beerStyleComment.findFirst({
where: { id },
});
if (!beerStyleComment) {
throw new ServerError('Beer style comment not found.', 404);
}
if (beerStyleComment.postedById !== user.id) {
throw new ServerError(
'You are not authorized to modify this beer style comment.',
403,
);
}
return next();
};
export const editBeerStyleComment = async (
req: EditCommentRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const updated = await updateBeerStyleCommentById({
id: req.query.id,
body: req.body,
});
return res.status(200).json({
success: true,
message: 'Comment updated successfully',
statusCode: 200,
payload: updated,
});
};
export const deleteBeerStyleComment = async (
req: CommentRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const { id } = req.query;
await DBClient.instance.beerStyleComment.delete({ where: { id } });
res.status(200).json({
success: true,
message: 'Comment deleted successfully',
statusCode: 200,
});
};

View File

@@ -0,0 +1,68 @@
import ServerError from '@/config/util/ServerError';
import DBClient from '@/prisma/DBClient';
import getBreweryCommentById from '@/services/BreweryComment/getBreweryCommentById';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiResponse } from 'next';
import { NextHandler } from 'next-connect';
import { z } from 'zod';
import { CommentRequest, EditCommentRequest } from '../requestTypes';
export const checkIfBreweryCommentOwner = async <
CommentRequestType extends CommentRequest,
>(
req: CommentRequestType,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
next: NextHandler,
) => {
const { id } = req.query;
const user = req.user!;
const comment = await getBreweryCommentById(id);
if (!comment) {
throw new ServerError('Comment not found', 404);
}
if (comment.postedById !== user.id) {
throw new ServerError('You are not authorized to modify this comment', 403);
}
return next();
};
export const editBreweryPostComment = async (
req: EditCommentRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const { id } = req.query;
const updated = await DBClient.instance.breweryComment.update({
where: { id },
data: {
content: req.body.content,
rating: req.body.rating,
updatedAt: new Date(),
},
});
return res.status(200).json({
success: true,
message: 'Comment updated successfully',
statusCode: 200,
payload: updated,
});
};
export const deleteBreweryPostComment = async (
req: CommentRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const { id } = req.query;
await DBClient.instance.breweryComment.delete({ where: { id } });
res.status(200).json({
success: true,
message: 'Comment deleted successfully',
statusCode: 200,
});
};

View File

@@ -0,0 +1,11 @@
import { UserExtendedNextApiRequest } from '@/config/auth/types';
import CreateCommentValidationSchema from '@/services/schema/CommentSchema/CreateCommentValidationSchema';
import { z } from 'zod';
export interface CommentRequest extends UserExtendedNextApiRequest {
query: { id: string };
}
export interface EditCommentRequest extends CommentRequest {
body: z.infer<typeof CreateCommentValidationSchema>;
}

View File

@@ -1,85 +1,22 @@
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 findBeerCommentById from '@/services/BeerComment/findBeerCommentById';
import CreateCommentValidationSchema from '@/services/schema/CommentSchema/CreateCommentValidationSchema';
import editBeerCommentById from '@/services/BeerComment/editBeerCommentById';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiResponse } from 'next';
import { createRouter, NextHandler } from 'next-connect';
import { createRouter } from 'next-connect';
import { z } from 'zod';
interface DeleteCommentRequest extends UserExtendedNextApiRequest {
query: { id: string };
}
interface EditCommentRequest extends UserExtendedNextApiRequest {
query: { id: string };
body: z.infer<typeof CreateCommentValidationSchema>;
}
const checkIfCommentOwner = async (
req: DeleteCommentRequest | EditCommentRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
next: NextHandler,
) => {
const { id } = req.query;
const user = req.user!;
const comment = await findBeerCommentById({ beerCommentId: id });
if (!comment) {
throw new ServerError('Comment not found', 404);
}
if (comment.postedBy.id !== user.id) {
throw new ServerError('You are not authorized to modify this comment', 403);
}
return next();
};
const editComment = async (
req: EditCommentRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const { id } = req.query;
const updated = await editBeerCommentById({
content: req.body.content,
rating: req.body.rating,
id,
});
res.status(200).json({
success: true,
message: 'Comment updated successfully',
statusCode: 200,
payload: updated,
});
};
const deleteComment = async (
req: DeleteCommentRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const { id } = req.query;
await DBClient.instance.beerComment.delete({
where: { id },
});
res.status(200).json({
success: true,
message: 'Comment deleted successfully',
statusCode: 200,
});
};
import { CommentRequest } from '@/controllers/requestTypes';
import {
checkIfBeerCommentOwner,
deleteBeerPostComment,
editBeerPostComment,
} from '@/controllers/beerComments';
const router = createRouter<
DeleteCommentRequest,
CommentRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>();
@@ -87,8 +24,8 @@ router
.delete(
validateRequest({ querySchema: z.object({ id: z.string().cuid() }) }),
getCurrentUser,
checkIfCommentOwner,
deleteComment,
checkIfBeerCommentOwner,
deleteBeerPostComment,
)
.put(
validateRequest({
@@ -96,8 +33,8 @@ router
bodySchema: CreateCommentValidationSchema,
}),
getCurrentUser,
checkIfCommentOwner,
editComment,
checkIfBeerCommentOwner,
editBeerPostComment,
);
const handler = router.handler(NextConnectOptions);

View File

@@ -1,85 +1,21 @@
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 {
checkIfBeerStyleCommentOwner,
deleteBeerStyleComment,
editBeerStyleComment,
} from '@/controllers/beerStyleComments';
import { CommentRequest } from '@/controllers/requestTypes';
import CreateCommentValidationSchema from '@/services/schema/CommentSchema/CreateCommentValidationSchema';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiResponse } from 'next';
import { createRouter, NextHandler } from 'next-connect';
import { createRouter } from 'next-connect';
import { z } from 'zod';
interface DeleteCommentRequest extends UserExtendedNextApiRequest {
query: { id: string };
}
interface EditCommentRequest extends UserExtendedNextApiRequest {
query: { id: string };
body: z.infer<typeof CreateCommentValidationSchema>;
}
const checkIfCommentOwner = async (
req: DeleteCommentRequest | EditCommentRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
next: NextHandler,
) => {
const { id } = req.query;
const user = req.user!;
const comment = await DBClient.instance.beerStyleComment.findFirst({ where: { id } });
if (!comment) {
throw new ServerError('Comment not found', 404);
}
if (comment.postedById !== user.id) {
throw new ServerError('You are not authorized to modify this comment', 403);
}
return next();
};
const editComment = async (
req: EditCommentRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const { id } = req.query;
const updated = await DBClient.instance.beerStyleComment.update({
where: { id },
data: {
content: req.body.content,
rating: req.body.rating,
updatedAt: new Date(),
},
});
return res.status(200).json({
success: true,
message: 'Comment updated successfully',
statusCode: 200,
payload: updated,
});
};
const deleteComment = async (
req: DeleteCommentRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const { id } = req.query;
await DBClient.instance.beerStyleComment.delete({ where: { id } });
res.status(200).json({
success: true,
message: 'Comment deleted successfully',
statusCode: 200,
});
};
const router = createRouter<
DeleteCommentRequest,
CommentRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>();
@@ -89,8 +25,8 @@ router
querySchema: z.object({ id: z.string().cuid() }),
}),
getCurrentUser,
checkIfCommentOwner,
deleteComment,
checkIfBeerStyleCommentOwner,
deleteBeerStyleComment,
)
.put(
validateRequest({
@@ -98,8 +34,8 @@ router
bodySchema: CreateCommentValidationSchema,
}),
getCurrentUser,
checkIfCommentOwner,
editComment,
checkIfBeerStyleCommentOwner,
editBeerStyleComment,
);
const handler = router.handler(NextConnectOptions);

View File

@@ -10,7 +10,7 @@ import { createRouter } from 'next-connect';
import { z } from 'zod';
import getCurrentUser from '@/config/nextConnect/middleware/getCurrentUser';
import { NextApiResponse } from 'next';
import CommentQueryResult from '@/services/schema/CommentSchema/CommentQueryResult';
import CreateCommentValidationSchema from '@/services/schema/CommentSchema/CreateCommentValidationSchema';
interface CreateCommentRequest extends UserExtendedNextApiRequest {
@@ -30,7 +30,7 @@ const createComment = async (
const beerPostId = req.query.id;
const newBeerComment: z.infer<typeof CommentQueryResult> = await createNewBeerComment({
const newBeerComment = await createNewBeerComment({
content,
rating,
beerPostId,

View File

@@ -20,8 +20,8 @@ interface EditBeerPostRequest extends BeerPostRequest {
body: z.infer<typeof EditBeerPostValidationSchema>;
}
const checkIfBeerPostOwner = async (
req: BeerPostRequest,
const checkIfBeerPostOwner = async <BeerPostRequestType extends BeerPostRequest>(
req: BeerPostRequestType,
res: NextApiResponse,
next: NextHandler,
) => {

View File

@@ -1,86 +1,22 @@
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 getBreweryCommentById from '@/services/BreweryComment/getBreweryCommentById';
import { checkIfBeerCommentOwner } from '@/controllers/beerComments';
import {
deleteBreweryPostComment,
editBreweryPostComment,
} from '@/controllers/breweryComments';
import { CommentRequest } from '@/controllers/requestTypes';
import CreateCommentValidationSchema from '@/services/schema/CommentSchema/CreateCommentValidationSchema';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiResponse } from 'next';
import { createRouter, NextHandler } from 'next-connect';
import { createRouter } from 'next-connect';
import { z } from 'zod';
interface DeleteCommentRequest extends UserExtendedNextApiRequest {
query: { id: string };
}
interface EditCommentRequest extends UserExtendedNextApiRequest {
query: { id: string };
body: z.infer<typeof CreateCommentValidationSchema>;
}
const checkIfCommentOwner = async (
req: DeleteCommentRequest | EditCommentRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
next: NextHandler,
) => {
const { id } = req.query;
const user = req.user!;
const comment = await getBreweryCommentById(id);
if (!comment) {
throw new ServerError('Comment not found', 404);
}
if (comment.postedById !== user.id) {
throw new ServerError('You are not authorized to modify this comment', 403);
}
return next();
};
const editComment = async (
req: EditCommentRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const { id } = req.query;
const updated = await DBClient.instance.breweryComment.update({
where: { id },
data: {
content: req.body.content,
rating: req.body.rating,
updatedAt: new Date(),
},
});
return res.status(200).json({
success: true,
message: 'Comment updated successfully',
statusCode: 200,
payload: updated,
});
};
const deleteComment = async (
req: DeleteCommentRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const { id } = req.query;
await DBClient.instance.breweryComment.delete({ where: { id } });
res.status(200).json({
success: true,
message: 'Comment deleted successfully',
statusCode: 200,
});
};
const router = createRouter<
DeleteCommentRequest,
CommentRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>();
@@ -90,8 +26,8 @@ router
querySchema: z.object({ id: z.string().cuid() }),
}),
getCurrentUser,
checkIfCommentOwner,
deleteComment,
checkIfBeerCommentOwner,
deleteBreweryPostComment,
)
.put(
validateRequest({
@@ -99,8 +35,8 @@ router
bodySchema: CreateCommentValidationSchema,
}),
getCurrentUser,
checkIfCommentOwner,
editComment,
checkIfBeerCommentOwner,
editBreweryPostComment,
);
const handler = router.handler(NextConnectOptions);

View File

@@ -35,10 +35,7 @@ const checkIfUserIsFollowedBySessionUser = async (
const currentUser = req.user!;
const userIsFollowedBySessionUser = await DBClient.instance.userFollow.findFirst({
where: {
followerId: currentUser.id,
followingId: id,
},
where: { followerId: currentUser.id, followingId: id },
});
if (!userIsFollowedBySessionUser) {

View File

@@ -1,108 +0,0 @@
import { UserExtendedNextApiRequest } from '@/config/auth/types';
import { singleUploadMiddleware } from '@/config/multer/uploadMiddleware';
import getCurrentUser from '@/config/nextConnect/middleware/getCurrentUser';
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
import DBClient from '@/prisma/DBClient';
import GetUserSchema from '@/services/User/schema/GetUserSchema';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiResponse } from 'next';
import { createRouter } from 'next-connect';
import { z } from 'zod';
interface UpdateProfileRequest extends UserExtendedNextApiRequest {
file: Express.Multer.File;
body: {
bio: string;
};
}
interface UpdateUserProfileByIdParams {
id: string;
data: {
bio: string;
avatar: {
alt: string;
path: string;
caption: string;
};
};
}
const updateUserProfileById = async ({ id, data }: UpdateUserProfileByIdParams) => {
const user: z.infer<typeof GetUserSchema> = await DBClient.instance.user.update({
where: { id },
data: {
bio: data.bio,
userAvatar: data.avatar
? {
upsert: {
create: {
alt: data.avatar.alt,
path: data.avatar.path,
caption: data.avatar.caption,
},
update: {
alt: data.avatar.alt,
path: data.avatar.path,
caption: data.avatar.caption,
},
},
}
: undefined,
},
select: {
id: true,
username: true,
email: true,
bio: true,
userAvatar: true,
accountIsVerified: true,
createdAt: true,
firstName: true,
lastName: true,
updatedAt: true,
dateOfBirth: true,
role: true,
},
});
return user;
};
const updateProfile = async (req: UpdateProfileRequest, res: NextApiResponse) => {
const { file, body, user } = req;
await updateUserProfileById({
id: user!.id,
data: {
bio: body.bio,
avatar: { alt: file.originalname, path: file.path, caption: '' },
},
});
res.status(200).json({
message: 'User confirmed successfully.',
statusCode: 200,
success: true,
});
};
const router = createRouter<
UpdateProfileRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>();
router.put(
getCurrentUser,
// @ts-expect-error
singleUploadMiddleware,
validateRequest({ bodySchema: z.object({ bio: z.string().max(1000) }) }),
updateProfile,
);
const handler = router.handler();
export default handler;
export const config = { api: { bodyParser: false } };

View File

@@ -3,13 +3,14 @@ import { singleUploadMiddleware } from '@/config/multer/uploadMiddleware';
import getCurrentUser from '@/config/nextConnect/middleware/getCurrentUser';
import ServerError from '@/config/util/ServerError';
import DBClient from '@/prisma/DBClient';
import GetUserSchema from '@/services/User/schema/GetUserSchema';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiResponse } from 'next';
import { NextHandler, createRouter } from 'next-connect';
import { z } from 'zod';
import updateUserAvatarById, {
UpdateUserAvatarByIdParams,
} from '@/services/UserAccount/UpdateUserAvatarByIdParams';
interface UpdateProfileRequest extends UserExtendedNextApiRequest {
file: Express.Multer.File;
@@ -18,57 +19,6 @@ interface UpdateProfileRequest extends UserExtendedNextApiRequest {
};
}
interface UpdateUserProfileByIdParams {
id: string;
data: {
avatar: {
alt: string;
path: string;
caption: string;
};
};
}
const updateUserAvatarById = async ({ id, data }: UpdateUserProfileByIdParams) => {
const user: z.infer<typeof GetUserSchema> = await DBClient.instance.user.update({
where: { id },
data: {
userAvatar: data.avatar
? {
upsert: {
create: {
alt: data.avatar.alt,
path: data.avatar.path,
caption: data.avatar.caption,
},
update: {
alt: data.avatar.alt,
path: data.avatar.path,
caption: data.avatar.caption,
},
},
}
: undefined,
},
select: {
id: true,
username: true,
email: true,
bio: true,
userAvatar: true,
accountIsVerified: true,
createdAt: true,
firstName: true,
lastName: true,
updatedAt: true,
dateOfBirth: true,
role: true,
},
});
return user;
};
const checkIfUserCanUpdateProfile = async (
req: UpdateProfileRequest,
res: NextApiResponse,
@@ -86,12 +36,13 @@ const checkIfUserCanUpdateProfile = async (
const updateProfile = async (req: UpdateProfileRequest, res: NextApiResponse) => {
const { file, user } = req;
await updateUserAvatarById({
id: user!.id,
data: {
avatar: { alt: file.originalname, path: file.path, caption: '' },
},
});
const avatar: UpdateUserAvatarByIdParams['data']['avatar'] = {
alt: file.originalname,
path: file.path,
caption: '',
};
await updateUserAvatarById({ id: user!.id, data: { avatar } });
res.status(200).json({
message: 'User avatar updated successfully.',
statusCode: 200,

View File

@@ -12,9 +12,7 @@ import { NextHandler, createRouter } from 'next-connect';
import { z } from 'zod';
interface UpdateProfileRequest extends UserExtendedNextApiRequest {
body: {
bio: string;
};
body: { bio: string };
}
interface UpdateUserProfileByIdParams {

View File

@@ -0,0 +1,23 @@
import DBClient from '@/prisma/DBClient';
import { z } from 'zod';
import CreateCommentValidationSchema from '../schema/CommentSchema/CreateCommentValidationSchema';
interface UpdateBeerStyleCommentByIdParams {
body: z.infer<typeof CreateCommentValidationSchema>;
id: string;
}
const updateBeerStyleCommentById = ({ body, id }: UpdateBeerStyleCommentByIdParams) => {
const { content, rating } = body;
return DBClient.instance.beerStyleComment.update({
where: { id },
data: {
content,
rating,
updatedAt: new Date(),
},
});
};
export default updateBeerStyleCommentById;

View File

@@ -0,0 +1,55 @@
import DBClient from '@/prisma/DBClient';
import GetUserSchema from '@/services/User/schema/GetUserSchema';
import { z } from 'zod';
export interface UpdateUserAvatarByIdParams {
id: string;
data: {
avatar: {
alt: string;
path: string;
caption: string;
};
};
}
const updateUserAvatarById = async ({ id, data }: UpdateUserAvatarByIdParams) => {
const user: z.infer<typeof GetUserSchema> = await DBClient.instance.user.update({
where: { id },
data: {
userAvatar: data.avatar
? {
upsert: {
create: {
alt: data.avatar.alt,
path: data.avatar.path,
caption: data.avatar.caption,
},
update: {
alt: data.avatar.alt,
path: data.avatar.path,
caption: data.avatar.caption,
},
},
}
: undefined,
},
select: {
id: true,
username: true,
email: true,
bio: true,
userAvatar: true,
accountIsVerified: true,
createdAt: true,
firstName: true,
lastName: true,
updatedAt: true,
dateOfBirth: true,
role: true,
},
});
return user;
};
export default updateUserAvatarById;