install zod for input validation

This commit is contained in:
Michi 2025-10-30 21:45:18 +01:00
parent 0b11cccf33
commit 9a4fd29fa5
4 changed files with 50 additions and 8 deletions

View file

@ -24,8 +24,12 @@ export class MissingParameter extends HTTPException{
}
export class InvalidParameter extends HTTPException{
constructor(paramName: string){
super(400, { message: `Provided parameter '${paramName}' is invalid.` })
constructor(paramName?: string){
super(400, { message:
paramName
? `Provided parameter '${paramName}' is invalid.`
: 'Provided invalid parameter.'
})
}
}

View file

@ -0,0 +1,15 @@
import * as z from 'zod'
import { zValidator } from '@hono/zod-validator'
import { InvalidParameter } from '../errors'
/**
* Custom Zod Validator Middleware with support for HTTP Exceptions
* @param type Part of HonoRequest object to get data from
* @param schema Zod Validation scheme (docs: https://zod.dev/api)
* @returns zValidator for running the validation
*/
export default function httpZValidator<T extends z.ZodTypeAny>(type: 'query' | 'json' | 'param' = 'query', schema: T){
return zValidator(type, schema, (result, c) => {
if(!result.success) throw new InvalidParameter();
})
}