More work on beer image upload

patFix schema so beer image and brewery image have createdBy column. Rename 'url' to 'path' in schema, add 'caption' column.
This commit is contained in:
Aaron William Po
2023-02-11 21:42:22 -05:00
parent 45cc10a009
commit 912008e68d
17 changed files with 193 additions and 58 deletions

View File

@@ -1,15 +1,32 @@
import { NextApiRequest, NextApiResponse } from 'next';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import type { NextApiRequest, NextApiResponse } from 'next';
import type { RequestHandler } from 'next-connect/dist/types/node';
import type { HandlerOptions } from 'next-connect/dist/types/types';
import { z } from 'zod';
import logger from '../pino/logger';
import ServerError from '../util/ServerError';
const NextConnectOptions = {
onNoMatch(req: NextApiRequest, res: NextApiResponse) {
type NextConnectOptionsT = HandlerOptions<
RequestHandler<
NextApiRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>
>;
const NextConnectOptions: NextConnectOptionsT = {
onNoMatch(req, res) {
res.status(405).json({
message: 'Method not allowed.',
statusCode: 405,
success: false,
});
},
onError(error: unknown, req: NextApiRequest, res: NextApiResponse) {
onError(error, req, res) {
if (process.env.NODE_ENV !== 'production') {
logger.error(error);
}
const message = error instanceof Error ? error.message : 'Internal server error.';
const statusCode = error instanceof ServerError ? error.statusCode : 500;
res.status(statusCode).json({

View File

@@ -0,0 +1,31 @@
import { UserExtendedNextApiRequest } from '@/config/auth/types';
import ServerError from '@/config/util/ServerError';
import getBeerPostById from '@/services/BeerPost/getBeerPostById';
import { NextApiResponse } from 'next';
import { NextHandler } from 'next-connect';
interface CheckIfBeerPostOwnerRequest extends UserExtendedNextApiRequest {
query: { id: string };
}
const checkIfBeerPostOwner = async <RequestType extends CheckIfBeerPostOwnerRequest>(
req: RequestType,
res: NextApiResponse,
next: NextHandler,
) => {
const { id } = req.query;
const user = req.user!;
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 are not authorized to edit this beer post', 403);
}
return next();
};
export default checkIfBeerPostOwner;

View File

@@ -28,10 +28,11 @@ const validateRequest =
}) =>
async (req: NextApiRequest, res: NextApiResponse, next: NextHandler) => {
if (bodySchema) {
const parsed = bodySchema.safeParse(req.body);
const parsed = bodySchema.safeParse(JSON.parse(JSON.stringify(req.body)));
if (!parsed.success) {
throw new ServerError('Invalid request body.', 400);
}
req.body = parsed.data;
}
if (querySchema) {