effect-schema

允许你根据 Drizzle ORM 的 schema 生成 effect schemas。

特性

用法

import { int4, cockroachTable, text, timestamp } from 'drizzle-orm/cockroach-core';
import { createInsertSchema, createSelectSchema, createUpdateSchema } from 'drizzle-orm/effect-schema';
import { Effect, Schema } from 'effect';

const users = cockroachTable('users', {
	id: int4().primaryKey().generatedAlwaysAsIdentity(),
	name: text().notNull(),
	email: text().notNull(),
	role: text({ enum: ['admin', 'user'] }).notNull(),
	createdAt: timestamp('created_at').notNull().defaultNow(),
});

// 用于插入用户的 schema - 可用于验证 API 请求
const UserInsert = createInsertSchema(users);

// 用于更新用户的 schema - 可用于验证 API 请求
const UserUpdate = createUpdateSchema(users);

// 用于选择用户的 schema - 可用于验证 API 响应
const UserSelect = createSelectSchema(users);

// 覆盖字段
const UserInsert = createInsertSchema(users, {
	role: Schema.String,
});

// 精炼字段 - 如果你想在字段最终变为 nullable/optional 之前先修改它们,这会很有用
const UserInsert = createInsertSchema(users, {
	id: (schema) => schema.check(Schema.isGreaterThanOrEqualTo(0)),
	role: Schema.String,
});

// 用法

const program = Effect.gen(function*() {
	const parsedUser = yield* Schema.decodeUnknownEffect(UserInsert)({
		name: 'John Doe',
		email: 'johndoe@test.com',
		role: 'admin',
	});
});