middleware
Unanswered
African Slender-snouted Crocodil… posted this in #help-forum
African Slender-snouted CrocodileOP
hello guys how i can add a middleware to my nextjs api . let when i make a request the middleware should make sure i am auth and a middle ware to check if the body or query is want i want similar to how it's done in express
3 Replies
African Slender-snouted CrocodileOP
here is what i am trying to acheive import { ZodSchema, ZodError } from 'zod'
import { Request, Response, NextFunction } from 'express'
import { catchAsync } from '.'
const validationMiddleware = ({
bodySchema,
querySchema,
paramsSchema,
}: {
bodySchema?: ZodSchema
querySchema?: ZodSchema
paramsSchema?: ZodSchema
}) => {
return catchAsync(
async (req: Request, res: Response, next: NextFunction) => {
try {
req.body = bodySchema ? bodySchema.parse(req.body) : {}
req.query = querySchema ? querySchema.parse(req.query) : {}
req.params = paramsSchema ? paramsSchema.parse(req.params) : {}
next()
} catch (error) {
if (error instanceof ZodError) {
const message = error.errors.map((err) => err.message)[0]
return res.status(400).json({
success: false,
message,
})
}
next(error)
}
},
)
}
export default validationMiddleware
import { Request, Response, NextFunction } from 'express'
import { catchAsync } from '.'
const validationMiddleware = ({
bodySchema,
querySchema,
paramsSchema,
}: {
bodySchema?: ZodSchema
querySchema?: ZodSchema
paramsSchema?: ZodSchema
}) => {
return catchAsync(
async (req: Request, res: Response, next: NextFunction) => {
try {
req.body = bodySchema ? bodySchema.parse(req.body) : {}
req.query = querySchema ? querySchema.parse(req.query) : {}
req.params = paramsSchema ? paramsSchema.parse(req.params) : {}
next()
} catch (error) {
if (error instanceof ZodError) {
const message = error.errors.map((err) => err.message)[0]
return res.status(400).json({
success: false,
message,
})
}
next(error)
}
},
)
}
export default validationMiddleware
@African Slender-snouted Crocodile resolved?