Skip to content

Commit

Permalink
feat: Zod schema validator for Fastify
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisGV04 committed Mar 6, 2024
1 parent 1a504a3 commit 8d183ac
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './errors';
export * from './locales';
export * from './plugins';
1 change: 1 addition & 0 deletions src/plugins/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './schema-validate';
12 changes: 12 additions & 0 deletions src/plugins/schema-validate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { FastifySchemaCompiler } from 'fastify';
import type { AnyZodObject } from 'zod';
import { SchemaValidationError } from '../errors';

/** Custom validator compiler that allows Zod to validate Fastify route schemas */
export const zodValidatorCompiler: FastifySchemaCompiler<AnyZodObject> = ({ schema }) => {
return (data) => {
const result = schema.safeParse(data);
if (!result.success) return { error: new SchemaValidationError(result.error) };
return { value: result.data };
};
};

0 comments on commit 8d183ac

Please sign in to comment.