zod-schema-db
v0.0.4
Published
Define your database schema using Zod. Generate functions to validate data and fake data.
Readme
Zod Schema Database
Define your database schema using Zod. Generate functions to validate data and fake data.
Installation
npm install zod-schema-databaseUsage
import { z } from 'zod-schema-database';
const userTableRaw = z.table({
id: z.generated(z.string()),
email: z.email(),
});
const userTable = userTableRaw.withRelations({
one: {
profile: z.relation(() => profileTableRaw),
},
});
const profileTableRaw = z.table({
id: z.generated(z.string()),
userId: z.string(),
bio: z.string(),
});
const profileTable = profileTableRaw.withRelations({
one: {
user: z.relation('userId', () => userTableRaw, 'id'),
},
});In this example, we define two versions of each table: one without relations (userTableRaw and profileTableRaw) and one with relations (userTable and profileTable). This is to prevent circular dependencies when TypeScript tries to resolve the types.
You can then use these tables to validate data, generate fake data, and more.
export const userSchema = userTable.select.withRelations();
export const userInsertSchema = userTable.insert;
export const userUpdateSchema = userTable.update;
export const generateUser = () => userSchema.fake();
export const generateUserToInsert = () => userSchema.fake();
export interface User extends z.infer<typeof userSchema> {}
export interface UserInsert extends z.infer<typeof userInsertSchema> {}With z.table, you get 3 schemas: select, insert, and update. These schemas Zod schemas, so you can use them as you would with any other Zod schema.
The insert and update schemas are designed to be used when inserting or updating data in your database so it will omit z.generated fields.
Features
- 🔒 Type Safety:
- As you define your database schema using Zod, you get full type safety in TypeScript.
- The
z.relationutility checks that the key types match between related tables, ensuring that your schema is consistent and valid.
- 🎭 Fake Data Generation: Easily generate fake data for testing and development with integrated Zocker.
Developed by Arthur Fontaine (GitHub).
