Zod Validation
npm install vovk-zod@draftZod 4
Validation with Zod 4 uses the vovk-zod package by importing the withZod function.
import { z } from 'zod';
import { withZod } from 'vovk-zod';
import { prefix, post, operation } from 'vovk';
@prefix('users')
export default class UserController {
@operation({
summary: 'Update user (Zod)',
description: 'Update user by ID with Zod validation',
})
@post('{id}')
static updateUser = withZod({
body: z
.object({
name: z.string().describe('User full name'),
age: z.number().min(0).max(120).describe('User age'),
email: z.string().email().describe('User email'),
})
.describe('User object'),
params: z.object({
id: z.uuid().describe('User ID'),
}),
query: z.object({
notify: z.enum(['email', 'push', 'none']).describe('Notification type'),
}),
output: z
.object({
success: z.boolean().describe('Success status'),
})
.describe('Response object'),
async handle(req, { id }) {
const { name, age } = await req.json();
const notify = req.nextUrl.searchParams.get('notify');
// do something with the data
console.log(`Updating user ${id}:`, { name, age, notify });
return {
success: true,
};
},
});
}This is built using Vovk.ts’s createStandardValidation function and serves as a convenience wrapper.
Zod 3
Zod 3 uses zod-to-json-schema to convert models to JSON Schema. Import withZod from vovk-zod/v3 and z from zod/v3 to use it. The syntax is identical to Zod 4:
import { z } from 'zod/v3';
import { withZod } from 'vovk-zod/v3';
import { prefix, post, operation } from 'vovk';
// ...existing code...Troubleshooting
The withZod implementation uses default options for toJSONSchema:
vovk-zod/src/index.ts
import { z } from 'zod';
import { createStandardValidation } from 'vovk';
export const withZod = createStandardValidation({
toJSONSchema: (model: z.core.$ZodType) => z.toJSONSchema(model),
});By default, Zod targets Draft 2020-12, which many current function calling APIs don’t support and may cause errors. If you need to override options, create a local withZod with custom toJSONSchema settings as shown in the Standard Schema section:
src/lib/withZod.ts
import { z } from 'zod';
import { createStandardValidation } from 'vovk';
export const withZod = createStandardValidation({
toJSONSchema: (model: z.core.$ZodType) => z.toJSONSchema(model, { target: 'draft-7' }),
});Last updated on