arktype

安装依赖

npm
yarn
pnpm
bun
npm i drizzle-orm@rc arktype

选择 schema

定义从数据库查询出的数据形状——可用于验证 API 响应。

import { int, mysqlTable, text } from 'drizzle-orm/mysql-core';
import { createSelectSchema } from 'drizzle-orm/arktype';
import type { ArkErrors } from "arktype";

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: ArkErrors | { id: number; name: string; age: number } = userSelectSchema(rows[0]); // 错误:上面的查询未返回 `age`

const rows = await db.select().from(users).limit(1);
const parsed: ArkErrors | { id: number; name: string; age: number } = userSelectSchema(rows[0]); // 将成功解析

也支持视图。

import { mysqlView } from 'drizzle-orm/mysql-core';
import { gt } from 'drizzle-orm';
import { createSelectSchema } from 'drizzle-orm/arktype';

const usersView = mysqlView('users_view').as((qb) => qb.select().from(users).where(gt(users.age, 18)));
const usersViewSchema = createSelectSchema(usersView);
const parsed: ArkErrors | { id: number; name: string; age: number } = usersViewSchema(...);

插入模式

定义要插入到数据库中的数据形状——可用于验证 API 请求。

import { int, mysqlTable, text } from 'drizzle-orm/mysql-core';
import { createInsertSchema } from 'drizzle-orm/arktype';
import type { ArkErrors } from "arktype";

const users = mysqlTable('users', {
  id: int().primaryKey().autoincrement(),
  name: text().notNull(),
  age: int().notNull()
});

const userInsertSchema = createInsertSchema(users);

const user = { name: 'John' };
const parsed: ArkErrors | { id?: number | undefined, name: string, age: number } = userInsertSchema(user); // 错误:未定义 `age`

const user = { name: 'Jane', age: 30 };
const parsed: ArkErrors | { id?: number | undefined, name: string, age: number } = userInsertSchema(user); // 将成功解析

if (parsed instanceof ArkErrors) {
  console.error(parsed.summary);
  process.exit(1);
}

await db.insert(users).values(parsed);

更新 schema

定义要在数据库中更新的数据形状 - 可用于验证 API 请求。

import { int, mysqlTable, text } from 'drizzle-orm/mysql-core';
import { createUpdateSchema } from 'drizzle-orm/arktype';
import { parse } from 'arktype';
import { ArkErrors } from "arktype";
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:  ArkErrors | { id?: number | undefined, name?: string | undefined, age?: number | undefined } = userUpdateSchema(user); // 将成功解析

if (parsed instanceof ArkErrors) {
  console.error(parsed.summary);
  process.exit(1);
}

await db.update(users).set(parsed).where(eq(users.name, 'Jane'));

优化

每个 create schema 函数都接受一个额外的可选参数,你可以用它来扩展、修改或完全覆盖某个字段的 schema。传入一个回调函数会对其进行扩展或修改,而提供一个 arktype schema 则会将其覆盖。

import { int, json, mysqlTable, text } from 'drizzle-orm/mysql-core';
import { createSelectSchema } from 'drizzle-orm/arktype';
import { ArkErrors, type } from 'arktype';

const users = mysqlTable('users', {
  id: int().primaryKey().autoincrement(),
  name: text().notNull(),
  bio: text(),
  preferences: json()
});

const userSelectSchema = createSelectSchema(users, {
  name: (schema) => pipe(schema, maxLength(20)), // 扩展 schema
  bio: (schema) => pipe(schema, maxLength(1000)), // 在变为可为 null/可选之前扩展 schema
  preferences: object({ theme: string() }) // 覆盖该字段,包括其 nullability
});

const parsed: ArkErrors | {
  id: number;
  name: string,
  bio?: string | undefined;
  preferences: {
    theme: string;
  };
} = userSelectSchema(...);

数据类型参考

mysql.boolean();

// Schema
type.boolean;
mysql.mysqlEnum('name', ['val1', 'val2']);

// Schema
type.enumerated('val1', '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.atMostLength(255)
mysql.blob({ mode: 'string' });
mysql.blob();

type.string.atMostLength(65_535)
mysql.mediumblob({ mode: 'string' });
mysql.mediumblob();

type.string.atMostLength(16_777_215)
mysql.longblob({ mode: 'string' });
mysql.longblob();

type.string.atMostLength(4_294_967_295)
mysql.char({ length: ... });

// Schema
type.string.exactlyLength(length);
mysql.varchar({ length: ... });

// Schema
type.string.atMostLength(length);
binary({ length: ... });

// Schema
type(`/^[01]{0,${length ?? "*"}}$/`)
mysql.varbinary({ length: ... });

// Schema
type(`/^[01]{0,${length ?? "*"}}$/`)
mysql.tinytext();

// Schema
type.string.atMostLength(255); // 无符号 8 位整数上限
mysql.text();

// Schema
type.string.atMostLength(65_535); // 无符号 16 位整数上限
mysql.mediumtext();

// Schema
type.string.atMostLength(16_777_215); // 无符号 24 位整数上限
mysql.longtext();

// Schema
type.string.atMostLength(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.enumerated(...enum);
mysql.tinyint();

// Schema
type.keywords.number.integer.atLeast(-128).atMost(127); // 8 位整数下限和上限
mysql.tinyint({ unsigned: true });

// Schema
type.keywords.number.integer.atLeast(0).atMost(255); // 无符号 8 位整数下限和上限
mysql.smallint();

// Schema
type.keywords.number.integer.atLeast(-32_768).atMost(32_767); // 16 位整数下限和上限
mysql.smallint({ unsigned: true });

// Schema
type.keywords.number.integer.atLeast(0).atMost(65_535); // 无符号 16 位整数下限和上限
mysql.float();

// Schema
type.number.atLeast(-8_388_608).atMost(8_388_607); // 24 位整数下限和上限
mysql.mediumint();

// Schema
type.keywords.number.integer.atLeast(-8_388_608).atMost(8_388_607); // 24 位整数下限和上限
mysql.float({ unsigned: true });

// Schema
type.number.atLeast(0).atMost(16_777_215); // 无符号 24 位整数下限和上限
mysql.mediumint({ unsigned: true });

// Schema
type.keywords.number.integer.atLeast(0).atMost(16_777_215); // 无符号 24 位整数下限和上限
mysql.int();

// Schema
type.keywords.number.integer.atLeast(-2_147_483_648).atMost(2_147_483_647); // 32 位整数下限和上限
mysql.int({ unsigned: true });

// Schema
type.keywords.number.integer.atLeast(0).atMost(4_294_967_295); // 无符号 32 位整数下限和上限
mysql.double();
mysql.real();

// Schema
type.number.atLeast(-140_737_488_355_328).atMost(140_737_488_355_327); // 48 位整数下限和上限
mysql.double({ unsigned: true });

// Schema
type.number.atLeast(0).atMost(281_474_976_710_655); // 无符号 48 位整数下限和上限
mysql.decimal({ mode: 'number' });

// Schema
type.number.atLeast(9_007_199_254_740_991).atMost(9_007_199_254_740_991)
mysql.decimal({ mode: 'bigint' });

// Schema
type.bigint.narrow(
  (value, ctx) => value < -9_223_372_036_854_775_808n ? ctx.mustBe('大于') : value > 9_223_372_036_854_775_807n ? ctx.mustBe('小于') : true
); // 64 位整数下限和上限
mysql.decimal({ mode: 'number', unsigned: true });

// Schema
type.number.atLeast(0).atMost(9_007_199_254_740_991)
mysql.decimal({ mode: 'bigint', unsigned: true });

// Schema
type.bigint.narrow(
  (value, ctx) => value < 0n ? ctx.mustBe('大于') : value > 18_446_744_073_709_551_615n ? ctx.mustBe('小于') : true
); // 无符号 64 位整数下限和上限
mysql.bigint({ mode: 'number' });

// Schema
type.keywords.number.integer.atLeast(-9_007_199_254_740_991).atMost(9_007_199_254_740_991); // JavaScript 最小和最大安全整数
mysql.bigint({ mode: 'number', unsigned: true });

// Schema
type.keywords.number.integer.atLeast(0).atMost(9_007_199_254_740_991); // JavaScript 最小和最大安全整数
mysql.bigint({ mode: 'string' });

// Schema
type.string.narrow((v, ctx) => {
	if (typeof v !== 'string') {
		return ctx.mustBe('一个字符串');
	}
	if (!(/^-?\d+$/.test(v))) {
		return ctx.mustBe('一个表示数字的字符串');
	}

	const bigint = BigInt(v);
	if (bigint < -9_223_372_036_854_775_808n) {
		return ctx.mustBe('大于');
	}
	if (bigint > 9_223_372_036_854_775_807n) {
		return ctx.mustBe('小于');
	}

	return true;
});
mysql.bigint({ mode: 'string', unsigned: true });

// Schema
type.string.narrow((v, ctx) => {
	if (typeof v !== 'string') {
		return ctx.mustBe('一个字符串');
	}
	if (!(/^\d+$/.test(v))) {
		return ctx.mustBe('一个表示数字的字符串');
	}

	const bigint = BigInt(v);
	if (bigint < 0) {
		return ctx.mustBe('大于');
	}
	if (bigint > 9_223_372_036_854_775_807n) {
		return ctx.mustBe('小于');
	}

	return true;
});
mysql.bigint({ mode: 'bigint' });

// Schema
type.bigint.narrow(
  (value, ctx) => value < -9_223_372_036_854_775_808n ? ctx.mustBe('大于') : value > 9_223_372_036_854_775_807n ? ctx.mustBe('小于') : true
); // 64 位整数下限和上限
mysql.bigint({ mode: 'bigint', unsigned: true });

// Schema
type.bigint.narrow(
  (value, ctx) => value < 0n ? ctx.mustBe('大于') : value > 18_446_744_073_709_551_615n ? ctx.mustBe('小于') : true
); // 无符号 64 位整数下限和上限
mysql.serial();

// Schema
type.keywords.number.integer.atLeast(0).atMost(9_007_199_254_740_991); // JavaScript 最大安全整数
mysql.year();

// Schema
type.keywords.number.integer.atLeast(1_901).atMost(2_155);
mysql.json();

// Schema
type('string | number | boolean | null').or(type('unknown.any[] | Record<string, unknown.any>'));