You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lib/src/validation/middleware.ts

23 lines
754 B

import {Request} from '../http/lifecycle/Request'
import {Validator} from './Validator'
import {ZodError} from 'zod'
import {HTTPStatus, left, right} from '../util'
import {json} from '../http/response/JSONResponseFactory'
export function validateMiddleware<T>(validator: Validator<T>) {
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
return (request: Request) => {
try {
const data = validator.parse(request.parsedInput)
return right(data)
} catch (e) {
if ( e instanceof ZodError ) {
// FIXME render this better
return left(json(e.formErrors).status(HTTPStatus.BAD_REQUEST))
}
throw e
}
}
}