Skip to content

Latest commit

 

History

History
70 lines (56 loc) · 2.4 KB

README.md

File metadata and controls

70 lines (56 loc) · 2.4 KB

drizzle-zod npm

npm zod version npm bundle size Discord License
If you know SQL, you know Drizzle ORM

drizzle-zod is a plugin for Drizzle ORM that allows you to generate Zod schemas from Drizzle ORM schemas.

Database Insert schema Select schema
PostgreSQL
MySQL
SQLite

Usage

import { pgEnum, pgTable, serial, text, timestamp } from 'drizzle-orm/pg-core';
import { z } from 'zod';
import { createInsertSchema } from 'drizzle-zod/pg';

const users = pgTable('users', {
  id: serial('id').primaryKey(),
  name: text('name').notNull(),
  email: text('email').notNull(),
  role: text<'admin' | 'user'>('role').notNull(),
  createdAt: timestamp('created_at').notNull().defaultNow(),
});

const newUserSchema = createInsertSchema(users);

// Transform keys to snake case
const newUserSchema = createInsertSchema(users, 'snake');

// Transform keys to camel case
const newUserSchema = createInsertSchema(users, 'camel');

// Override the fields
const newUserSchema = createInsertSchema(users, {
  // this is required for runtime validation of text enum types, otherwise z.string() will be used
  role: z.enum(['admin', 'user']),
});

// Refine the fields
const newUserSchema = createInsertSchema(users, (schema) => ({
  id: schema.id.positive(),
  email: schema.email.email(),
  role: z.enum(['admin', 'user']),
}));

const newUserSchema = createInsertSchema(users, 'snake', (schema) => ({
  created_at: schema.createdAt.min(new Date()),
}));

// Usage

const user = newUserSchema.parse({
  name: 'John Doe',
  email: '[email protected]',
  role: 'admin',
});

// Zod schema type is also inferred from the table schema, so you have full type safety
const requestSchema = newUserSchema.pick({ name: true, email: true });