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

@@ -3,11 +3,11 @@ import { NextHandler } from 'next-connect';
import findUserById from '@/services/user/findUserById';
import ServerError from '@/config/util/ServerError';
import { getLoginSession } from '../session';
import { ExtendedNextApiRequest } from '../types';
import { UserExtendedNextApiRequest } from '../types';
/** Get the current user from the session. Adds the user to the request object. */
const getCurrentUser = async (
req: ExtendedNextApiRequest,
req: UserExtendedNextApiRequest,
res: NextApiResponse,
next: NextHandler,
) => {

View File

@@ -15,7 +15,7 @@ export const UserSessionSchema = BasicUserInfoSchema.merge(
}),
);
export interface ExtendedNextApiRequest extends NextApiRequest {
export interface UserExtendedNextApiRequest extends NextApiRequest {
user?: z.infer<typeof GetUserSchema>;
}

View File

@@ -0,0 +1,48 @@
import ServerError from '@/config/util/ServerError';
import { NextApiRequest, NextApiResponse } from 'next';
import { NextHandler } from 'next-connect';
import { z } from 'zod';
/**
* Middleware to validate the request body and/or query against a zod schema.
*
* @example
* const handler = nextConnect(NextConnectConfig).post(
* validateRequest({ bodySchema: BeerPostValidationSchema }),
* getCurrentUser,
* createBeerPost,
* );
*
* @param args
* @param args.bodySchema The body schema to validate against.
* @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) => {
if (bodySchema) {
const parsed = bodySchema.safeParse(req.body);
if (!parsed.success) {
throw new ServerError('Invalid request body.', 400);
}
}
if (querySchema) {
const parsed = querySchema.safeParse(req.query);
if (!parsed.success) {
throw new ServerError(parsed.error.message, 400);
}
req.query = parsed.data;
}
next();
};
export default validateRequest;