typebox-legacy
安装依赖
npm
yarn
pnpm
bun
npm i drizzle-orm@rc @sinclair/typebox
选择模式
定义从数据库查询的数据形状 - 可用于验证 API 响应。
import { int, mysqlTable, text } from 'drizzle-orm/mysql-core';
import { createSelectSchema } from 'drizzle-orm/typebox-legacy';
import { Value } from '@sinclair/typebox/value';
const users = mysqlTable('users', {
id: int().primaryKey().autoincrement(),
name: text().notNull(),
age: int().notNull()
});
const userSelectSchema = createSelectSchema(users);
const rows = await db.select({ id: users.id, name: users.name }).from(users).limit(1);
const parsed: { id: number; name: string; age: number } = Value.Parse(userSelectSchema, rows[0]); // 错误:上面的查询中未返回 `age`
const rows = await db.select().from(users).limit(1);
const parsed: { id: number; name: string; age: number } = Value.Parse(userSelectSchema, rows[0]); // 将会成功解析也支持视图。
import { mysqlView } from 'drizzle-orm/mysql-core';
import { gt } from 'drizzle-orm';
import { createSelectSchema } from 'drizzle-orm/typebox-legacy';
import { Value } from '@sinclair/typebox/value';
const usersView = mysqlView('users_view').as((qb) => qb.select().from(users).where(gt(users.age, 18)));
const usersViewSchema = createSelectSchema(usersView);
const parsed: { id: number; name: string; age: number } = Value.Parse(usersViewSchema, ...);插入模式
定义要插入到数据库中的数据形状——可用于验证 API 请求。
import { int, mysqlTable, text } from 'drizzle-orm/mysql-core';
import { createInsertSchema } from 'drizzle-orm/typebox-legacy';
import { Value } from '@sinclair/typebox/value';
const users = mysqlTable('users', {
id: int().primaryKey().autoincrement(),
name: text().notNull(),
age: int().notNull()
});
const userInsertSchema = createInsertSchema(users);
const user = { name: 'John' };
const parsed: { id?: number | undefined, name: string, age: number } = Value.Parse(userInsertSchema, user); // 错误:未定义 `age`
const user = { name: 'Jane', age: 30 };
const parsed: { id?: number | undefined, name: string, age: number } = Value.Parse(userInsertSchema, user); // 将成功解析
await db.insert(users).values(parsed);更新模式
定义要在数据库中更新的数据结构——可用于验证 API 请求。
import { int, mysqlTable, text } from 'drizzle-orm/mysql-core';
import { createUpdateSchema } from 'drizzle-orm/typebox-legacy';
import { Value } from '@sinclair/typebox/value';
import { eq } from "drizzle-orm";
const users = mysqlTable('users', {
id: int().primaryKey().autoincrement(),
name: text().notNull(),
age: int().notNull()
});
const userUpdateSchema = createUpdateSchema(users);
const user = { age: 35 };
const parsed: { id?: number | undefined, name?: string | undefined, age?: number | undefined } = Value.Parse(userUpdateSchema, user); // 将成功解析
await db.update(users).set(parsed).where(eq(users.name, 'Jane'));优化
每个 create schema 函数都接受一个额外的可选参数,你可以用它来扩展、修改或完全覆盖某个字段的 schema。定义一个回调函数会进行扩展或修改,而提供一个 Typebox schema 则会覆盖它。
import { int, json, mysqlTable, text } from 'drizzle-orm/mysql-core';
import { createSelectSchema } from 'drizzle-orm/typebox-legacy';
import { Type } from '@sinclair/typebox';
import { Value } from '@sinclair/typebox/value';
const users = mysqlTable('users', {
id: int().primaryKey().autoincrement(),
name: text().notNull(),
bio: text(),
preferences: json()
});
const userSelectSchema = createSelectSchema(users, {
name: (schema) => Type.String({ ...schema, maxLength: 20 }), // 扩展 schema
bio: (schema) => Type.String({ ...schema, maxLength: 1000 }), // 在变为可空/可选之前扩展 schema
preferences: Type.Object({ theme: Type.String() }) // 覆盖该字段,包括其可空性
});
const parsed: {
id: number;
name: string,
bio: string | null;
preferences: {
theme: string;
};
} = Value.Parse(userSelectSchema, ...);工厂函数
对于更高级的使用场景,你可以使用 createSchemaFactory 函数。
用例:使用扩展的 Typebox 实例
import { int, mysqlTable, text } from 'drizzle-orm/mysql-core';
import { createSchemaFactory } from 'drizzle-orm/typebox';
import { t } from 'elysia'; // 扩展的 Typebox 实例
const users = mysqlTable('users', {
id: int().primaryKey().autoincrement(),
name: text().notNull(),
age: int().notNull()
});
const { createInsertSchema } = createSchemaFactory({ typeboxInstance: t });
const userInsertSchema = createInsertSchema(users, {
// 我们现在可以使用扩展实例
name: (schema) => t.Number({ ...schema, error: "`name` 必须是字符串" })
});数据类型参考
mysql.boolean();
// Schema
Type.Boolean();mysql.mysqlEnum('name', ['val1', 'val2']);
// Schema
Type.Enum({ 'val1': 'val1', 'val2': 'val2' });mysql.date({ mode: 'date' });
mysql.datetime({ mode: 'date' });
mysql.timestamp({ mode: 'date' });
// Schema
Type.Date();mysql.binary();
mysql.date({ mode: 'string' });
mysql.datetime({ mode: 'string' });
mysql.decimal();
mysql.time();
mysql.timestamp({ mode: 'string' });
mysql.varbinary();
// Schema
Type.String();mysql.tinyblob({ mode: 'string' });
mysql.tinyblob();
Type.String({ maxLength: 255 })mysql.blob({ mode: 'string' });
mysql.blob();
Type.String({ maxLength: 65_535 })mysql.mediumblob({ mode: 'string' });
mysql.mediumblob();
Type.String({ maxLength: 16_777_215 })mysql.longblob({ mode: 'string' });
mysql.longblob();
Type.String({ maxLength: 4_294_967_295 })mysql.char({ length: ... });
// Schema
Type.String({ minLength: length, maxLength: length });mysql.varchar({ length: ... });
// Schema
Type.String({ maxLength: length });binary({ length: ... });
// Schema
Type.RegExp(/^[01]*$/, { maxLength: length })mysql.varbinary({ length: ... });
// Schema
Type.RegExp(/^[01]*$/, { maxLength: length })mysql.tinytext();
// Schema
Type.String({ maxLength: 255 }); // 无符号 8 位整数上限mysql.text();
// Schema
Type.String({ maxLength: 65_535 }); // 无符号 16 位整数上限mysql.mediumtext();
// Schema
Type.String({ maxLength: 16_777_215 }); // 无符号 24 位整数上限mysql.longtext();
// Schema
Type.String({ maxLength: 4_294_967_295 }); // 无符号 32 位整数上限mysql.tinytext({ enum: ... });
mysql.mediumtext({ enum: ... });
mysql.text({ enum: ... });
mysql.longtext({ enum: ... });
mysql.char({ enum: ... });
mysql.varchar({ enum: ... });
// Schema
Type.Enum(enum);mysql.tinyint();
// Schema
Type.Integer({ minimum: -128, maximum: 127 }); // 8 位整数下限和上限mysql.tinyint({ unsigned: true });
// Schema
Type.Integer({ minimum: 0, maximum: 255 }); // 无符号 8 位整数下限和上限mysql.smallint();
// Schema
Type.Integer({ minimum: -32_768, maximum: 32_767 }); // 16 位整数下限和上限mysql.smallint({ unsigned: true });
// Schema
Type.Integer({ minimum: 0, maximum: 65_535 }); // 无符号 16 位整数下限和上限mysql.float();
// Schema
Type.Number().min(-8_388_608).max(8_388_607); // 24 位整数下限和上限mysql.mediumint();
// Schema
Type.Integer({ minimum: -8_388_608, maximum: 8_388_607 }); // 24 位整数下限和上限mysql.float({ unsigned: true });
// Schema
Type.Number({ minimum: 0, maximum: 16_777_215 }); // 无符号 24 位整数下限和上限mysql.mediumint({ unsigned: true });
// Schema
Type.Integer({ minimum: 0, maximum: 16_777_215 }); // 无符号 24 位整数下限和上限mysql.int();
// Schema
Type.Integer({ minimum: -2_147_483_648, maximum: 2_147_483_647 }); // 32 位整数下限和上限mysql.int({ unsigned: true });
// Schema
Type.Integer({ minimum: 0, maximum: 4_294_967_295 }); // 拼写错误:unsigned 32 位整数下限和上限mysql.double();
mysql.real();
// Schema
Type.Number({ minimum: -140_737_488_355_328, maximum: 140_737_488_355_327 }); // 48 位整数下限和上限mysql.double({ unsigned: true });
// Schema
Type.Numer({ minimum: 0, maximum: 281_474_976_710_655 }); // 无符号 48 位整数下限和上限mysql.decimal({ mode: 'number' });
// Schema
Type.Number({ minimum: -9_007_199_254_740_991, maximum: 9_007_199_254_740_991 });mysql.decimal({ mode: 'bigint' });
// Schema
Type.BigInt({ minimum: -9_223_372_036_854_775_808n, maximum: 9_223_372_036_854_775_807n });mysql.decimal({ mode: 'number', unsigned: true });
// Schema
Type.Number({ minimum: 0, maximum: 9_007_199_254_740_991 });mysql.decimal({ mode: 'bigint', unsigned: true });
// Schema
Type.BigInt({ minimum: 0, maximum: 18_446_744_073_709_551_615n });mysql.bigint({ mode: 'number' });
// Schema
Type.Integer({ minimum: -9_007_199_254_740_991, maximum: 9_007_199_254_740_991 }); // JavaScript 最小和最大安全整数mysql.bigint({ mode: 'number', unsigned: true });
// Schema
Type.Integer({ minimum: 0, maximum: 9_007_199_254_740_991 }); // JavaScript 最小和最大安全整数mysql.bigint({ mode: 'string' });
// Schema
TypeRegistry.Set('BigIntStringMode', (_, value) => {
if (typeof value !== 'string' || !(/^-?\d+$/.test(value))) {
return false;
}
const bigint = BigInt(value);
if (bigint < -9_223_372_036_854_775_808n || bigint > 9_223_372_036_854_775_807n) {
return false;
}
return true;
});
{ [Kind]: 'BigIntStringMode', type: 'string' }mysql.bigint({ mode: 'string', unsigned: true });
// Schema
TypeRegistry.Set('UnsignedBigIntStringMode', (_, value) => {
if (typeof value !== 'string' || !(/^\d+$/.test(value))) {
return false;
}
const bigint = BigInt(value);
if (bigint < 0 || bigint > 9_223_372_036_854_775_807n) {
return false;
}
return true;
});
{ [Kind]: 'UnsignedBigIntStringMode', type: 'string' }mysql.bigint({ mode: 'bigint' });
// Schema
Type.BigInt({ minimum: -9_223_372_036_854_775_808n, maximum: 9_223_372_036_854_775_807n }); // 64 位整数下限和上限mysql.bigint({ mode: 'bigint', unsigned: true });
// Schema
Type.BigInt({ minimum: 0, maximum: 18_446_744_073_709_551_615n }); // 无符号 64 位整数下限和上限mysql.serial();
Type.Integer({ minimum: 0, maximum: 9_007_199_254_740_991 })mysql.year();
// Schema
Type.Integer({ minimum: 1_901, maximum: 2_155 });mysql.json();
// Schema
Type.Recursive((self) => Type.Union([Type.Union([Type.String(), Type.Number(), Type.Boolean(), Type.Null()]), Type.Array(self), Type.Record(Type.String(), self)]));