从 drizzle-orm@1.0.0-beta.15 开始,drizzle-typebox 已被弃用,取而代之的是 Drizzle ORM 自身内置的一流模式生成支持
你仍然可以使用 drizzle-typebox 包,但所有新的更新将直接添加到 Drizzle ORM 中
此版本的 typebox 使用了新的 typebox 包
从 drizzle-orm@1.0.0-beta.15 开始,drizzle-typebox 已被弃用,取而代之的是 Drizzle ORM 自身内置的一流模式生成支持
你仍然可以使用 drizzle-typebox 包,但所有新的更新将直接添加到 Drizzle ORM 中
此版本的 typebox 使用了新的 typebox 包
npm i drizzle-orm typebox
允许你从 Drizzle ORM 模式生成 typebox 模式
功能
import { pgEnum, pgTable, serial, text, timestamp } from 'drizzle-orm/pg-core';
import { createInsertSchema, createSelectSchema, createUpdateSchema } from 'drizzle-orm/typebox';
import { Type } from 'typebox';
import { Value } from 'typebox/value';
const users = pgTable('users', {
id: serial('id').primaryKey(),
name: text('name').notNull(),
email: text('email').notNull(),
role: text('role', { enum: ['admin', 'user'] }).notNull(),
createdAt: timestamp('created_at').notNull().defaultNow(),
});
// 用于插入用户的模式 - 可用于验证 API 请求
const insertUserSchema = createInsertSchema(users);
// 用于更新用户的模式 - 可用于验证 API 请求
const updateUserSchema = createUpdateSchema(users);
// 用于选择用户的模式 - 可用于验证 API 响应
const selectUserSchema = createSelectSchema(users);
// 覆盖字段
const insertUserSchema = createInsertSchema(users, {
role: Type.String(),
});
// 精炼字段 - 如果你想在字段在最终模式中变为可空/可选之前修改字段,这很有用
const insertUserSchema = createInsertSchema(users, {
id: (schema) => Type.Number({ ...schema, minimum: 0 }),
role: Type.String(),
});
// 用法示例
const isUserValid: boolean = Value.Check(insertUserSchema, {
name: 'John Doe',
email: 'johndoe@test.com',
role: 'admin',
});