Update api routes to use authenticated user

This commit is contained in:
Aaron William Po
2023-02-06 19:01:01 -05:00
parent 9a9d8bcb94
commit 3626e3de44
12 changed files with 190 additions and 143 deletions

View File

@@ -1,27 +1,31 @@
import validateRequest from '@/config/zod/middleware/validateRequest';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { UserExtendedNextApiRequest } from '@/config/auth/types';
import NextConnectConfig from '@/config/nextConnect/NextConnectConfig';
import ServerError from '@/config/util/ServerError';
import createNewBeerComment from '@/services/BeerComment/createNewBeerComment';
import { BeerCommentQueryResultT } from '@/services/BeerComment/schema/BeerCommentQueryResult';
import BeerCommentValidationSchema from '@/services/BeerComment/schema/CreateBeerCommentValidationSchema';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiHandler } from 'next';
import nextConnect from 'next-connect';
import { z } from 'zod';
import getCurrentUser from '@/config/auth/middleware/getCurrentUser';
import { NextApiResponse } from 'next';
const createComment: NextApiHandler<z.infer<typeof APIResponseValidationSchema>> = async (
req,
res,
interface CreateCommentRequest extends UserExtendedNextApiRequest {
body: z.infer<typeof BeerCommentValidationSchema>;
}
const createComment = async (
req: CreateCommentRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const cleanedReqBody = BeerCommentValidationSchema.safeParse(req.body);
if (!cleanedReqBody.success) {
throw new ServerError('Invalid request body', 400);
}
const { content, rating, beerPostId } = cleanedReqBody.data;
const { content, rating, beerPostId } = req.body;
const newBeerComment: BeerCommentQueryResultT = await createNewBeerComment({
content,
rating,
beerPostId,
userId: req.user!.id,
});
res.status(201).json({
@@ -32,6 +36,10 @@ const createComment: NextApiHandler<z.infer<typeof APIResponseValidationSchema>>
});
};
const handler = nextConnect(NextConnectConfig).post(createComment);
const handler = nextConnect(NextConnectConfig).post(
validateRequest({ bodySchema: BeerCommentValidationSchema }),
getCurrentUser,
createComment,
);
export default handler;