typebox
安装依赖
npm
yarn
pnpm
bun
npm i drizzle-orm@rc typebox
允许你根据 Drizzle ORM 模式生成 typebox 模式
功能
- 为表创建 select 模式。
- 为表创建 insert 和 update 模式。
- 支持的方言:MSSQL。
用法
import { int, mssqlTable, text, datetime2 } from 'drizzle-orm/mssql-core';
import { createInsertSchema, createSelectSchema, createUpdateSchema } from 'drizzle-orm/typebox';
import { Type } from 'typebox';
import { Value } from 'typebox/value';
const users = mssqlTable('users', {
id: int().primaryKey().identity(),
name: text().notNull(),
email: text().notNull(),
role: text({ enum: ['admin', 'user'] }).notNull(),
createdAt: datetime2('created_at').notNull(),
});
// 用于插入用户的模式 - 可用于验证 API 请求
const insertUserSchema = createInsertSchema(users);
// 用于更新用户的模式 - 可用于验证 API 请求
const updateUserSchema = createUpdateSchema(users);
// 用于选择用户的模式 - 可用于验证 API 响应
const selectUserSchema = createSelectSchema(users);
// 覆盖字段
const insertUserSchema = createInsertSchema(users, {
role: Type.String(),
});
// 精化字段 - 如果你想在字段在最终模式中变为 nullable/optional 之前对其进行更改,这很有用
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',
});