@geekmidas/db (英语)
为Kysely提供灵活的交易管理的数据库服务。 提供帮助者以类型安全的方式处理数据库连接和交易.
特征
- ✅ 灵活交易处理: 与Kysely公司、交易和受控交易公司合作
- ✅ 自动交易检测: 嵌入时重用已存在的交易
- ✅ 类型安全: 具有通用数据库图案的完整类型脚本支持
- ✅ 连接摘要: 所有数据库连接类型的单一帮助
- ✅ 无依赖: 只依赖 Kysely 的同行
安装
pnpm add @geekmidas/db
同伴依赖关系
pnpm add kysely pg
快速启动
import { withTransaction } from '@geekmidas/db/kysely';
import type { DatabaseConnection } from '@geekmidas/db/kysely';
import { Kysely } from 'kysely';
interface Database {
users: {
id: string;
email: string;
name: string;
};
posts: {
id: string;
userId: string;
title: string;
};
}
async function createUserWithPost(
db: DatabaseConnection<Database>,
userData: { email: string; name: string },
postData: { title: string }
) {
return withTransaction(db, async (trx) => {
// Create user
const user = await trx
.insertInto('users')
.values(userData)
.returningAll()
.executeTakeFirstOrThrow();
// Create post for user
const post = await trx
.insertInto('posts')
.values({
userId: user.id,
title: postData.title
})
.returningAll()
.executeTakeFirstOrThrow();
return { user, post };
});
}
API 参考
withTransaction
执行交易中的召回。 如果连接已经是交易, 它会重用它 。 否则,它会产生新的交易.
function withTransaction<DB, T>(
db: DatabaseConnection<DB>,
cb: (trx: Transaction<DB>) => Promise<T>
): Promise<T>
参数:
db- 数据库连接(Kysely, 交易,或控制交易)cb- 接收交易的召回功能
回返情况:
- 承诺解决回调值
DatabaseConnection<T>
所有支持的数据库连接类型的类型联盟 :
type DatabaseConnection<T> =
| Kysely<T>
| Transaction<T>
| ControlledTransaction<T>;
用法实例
基本交易
import { withTransaction } from '@geekmidas/db/kysely';
import { Kysely } from 'kysely';
const db = new Kysely<Database>({ /* config */ });
async function transferFunds(fromId: string, toId: string, amount: number) {
return withTransaction(db, async (trx) => {
// Deduct from sender
await trx
.updateTable('accounts')
.set({ balance: sql`balance - ${amount}` })
.where('id', '=', fromId)
.execute();
// Add to receiver
await trx
.updateTable('accounts')
.set({ balance: sql`balance + ${amount}` })
.where('id', '=', toId)
.execute();
return { success: true };
});
}
嵌入式交易
帮助者自动检测现有交易并重用:
async function createUser(
db: DatabaseConnection<Database>,
email: string
) {
return withTransaction(db, async (trx) => {
const user = await trx
.insertInto('users')
.values({ email })
.returningAll()
.executeTakeFirstOrThrow();
// This will reuse the same transaction
await createAuditLog(trx, 'user_created', user.id);
return user;
});
}
async function createAuditLog(
db: DatabaseConnection<Database>,
action: string,
userId: string
) {
// If db is already a transaction, it's reused
return withTransaction(db, async (trx) => {
await trx
.insertInto('audit_logs')
.values({ action, userId, timestamp: new Date() })
.execute();
});
}
仓库模式
使用 DatabaseConnection 用于灵活性的存储器类型 :
import type { DatabaseConnection } from '@geekmidas/db/kysely';
import { withTransaction } from '@geekmidas/db/kysely';
class UserRepository {
constructor(private db: DatabaseConnection<Database>) {}
async create(data: NewUser): Promise<User> {
return withTransaction(this.db, async (trx) => {
return trx
.insertInto('users')
.values(data)
.returningAll()
.executeTakeFirstOrThrow();
});
}
async update(id: string, data: UserUpdate): Promise<User> {
return withTransaction(this.db, async (trx) => {
return trx
.updateTable('users')
.set(data)
.where('id', '=', id)
.returningAll()
.executeTakeFirstOrThrow();
});
}
}
// Can be used with any connection type
const db = new Kysely<Database>({ /* config */ });
const repo = new UserRepository(db);
// Or within a transaction
await withTransaction(db, async (trx) => {
const repo = new UserRepository(trx);
await repo.create({ email: '[email protected]' });
});
有交易的服务模式
import type { DatabaseConnection } from '@geekmidas/db/kysely';
import { withTransaction } from '@geekmidas/db/kysely';
class OrderService {
constructor(
private db: DatabaseConnection<Database>,
private inventoryService: InventoryService,
private paymentService: PaymentService
) {}
async createOrder(
userId: string,
items: OrderItem[]
): Promise<Order> {
return withTransaction(this.db, async (trx) => {
// All operations share the same transaction
const order = await trx
.insertInto('orders')
.values({ userId, status: 'pending' })
.returningAll()
.executeTakeFirstOrThrow();
// These services can accept the transaction
await this.inventoryService.reserveItems(trx, items);
await this.paymentService.processPayment(trx, order.id);
// Update order status
return trx
.updateTable('orders')
.set({ status: 'completed' })
.where('id', '=', order.id)
.returningAll()
.executeTakeFirstOrThrow();
});
}
}
class InventoryService {
async reserveItems(
db: DatabaseConnection<Database>,
items: OrderItem[]
) {
return withTransaction(db, async (trx) => {
for (const item of items) {
await trx
.updateTable('inventory')
.set({ reserved: sql`reserved + ${item.quantity}` })
.where('productId', '=', item.productId)
.execute();
}
});
}
}
处理错误
交易自动滚回错误 :
import { withTransaction } from '@geekmidas/db/kysely';
async function processOrder(db: DatabaseConnection<Database>, orderId: string) {
try {
return await withTransaction(db, async (trx) => {
const order = await trx
.selectFrom('orders')
.where('id', '=', orderId)
.selectAll()
.executeTakeFirstOrThrow();
if (order.status !== 'pending') {
throw new Error('Order already processed');
}
// Update order
await trx
.updateTable('orders')
.set({ status: 'processing' })
.where('id', '=', orderId)
.execute();
// If this throws, the entire transaction rolls back
await processPayment(trx, orderId);
return order;
});
} catch (error) {
console.error('Transaction failed:', error);
// Transaction has been rolled back
throw error;
}
}
用交易测试
使用交易进行测试隔离 :
import { describe, it, beforeEach, afterEach } from 'vitest';
import type { Transaction } from 'kysely';
describe('UserRepository', () => {
let trx: Transaction<Database>;
beforeEach(async () => {
trx = await db.transaction().execute(async (t) => t);
});
afterEach(async () => {
await trx.rollback();
});
it('should create user', async () => {
const repo = new UserRepository(trx);
const user = await repo.create({ email: '[email protected]' });
expect(user.email).toBe('[email protected]');
// Transaction will be rolled back after test
});
});
类型安全
软件包为数据库操作提供了完整的类型安全:
import type { DatabaseConnection } from '@geekmidas/db/kysely';
import { withTransaction } from '@geekmidas/db/kysely';
interface Database {
users: {
id: Generated<string>;
email: string;
name: string | null;
};
}
function updateUser(
db: DatabaseConnection<Database>,
id: string,
data: { name: string }
) {
return withTransaction(db, async (trx) => {
// Full autocomplete and type checking
return trx
.updateTable('users')
.set(data) // Type-checked against users table
.where('id', '=', id)
.returningAll()
.executeTakeFirstOrThrow();
});
}
高级图案
工作模式股
class UnitOfWork {
private transaction: Transaction<Database> | null = null;
constructor(private db: Kysely<Database>) {}
async begin() {
this.transaction = await this.db.transaction().execute(async (t) => t);
}
async commit() {
if (this.transaction) {
await this.transaction.commit();
this.transaction = null;
}
}
async rollback() {
if (this.transaction) {
await this.transaction.rollback();
this.transaction = null;
}
}
getConnection(): DatabaseConnection<Database> {
return this.transaction || this.db;
}
}
// Usage
const uow = new UnitOfWork(db);
await uow.begin();
try {
const userRepo = new UserRepository(uow.getConnection());
const orderRepo = new OrderRepository(uow.getConnection());
await userRepo.create({ email: '[email protected]' });
await orderRepo.create({ userId: '123' });
await uow.commit();
} catch (error) {
await uow.rollback();
throw error;
}
连接集合
import { Pool } from 'pg';
import { Kysely, PostgresDialect } from 'kysely';
const pool = new Pool({
host: 'localhost',
database: 'mydb',
max: 10
});
const db = new Kysely<Database>({
dialect: new PostgresDialect({ pool })
});
// Use with withTransaction
async function processData(data: unknown[]) {
return withTransaction(db, async (trx) => {
// Each transaction gets a connection from the pool
for (const item of data) {
await trx.insertInto('items').values(item).execute();
}
});
}
最佳做法
-
使用数据库连接类型: 接受
DatabaseConnection与交易有关的职能async function myFunction(db: DatabaseConnection<Database>) { } -
让交易处理重用: 不要手动检查交易类型
// Good await withTransaction(db, async (trx) => { }); // Avoid if (db.isTransaction) { /* ... */ } else { /* ... */ } -
保持交易简短: 迅速执行以避免阻塞
// Good await withTransaction(db, async (trx) => { await trx.insertInto('users').values(data).execute(); }); // Avoid long-running operations await withTransaction(db, async (trx) => { await fetch('https://api.example.com'); // Bad! }); -
处理错误: 让交易自动滚回错误
-
测试: 使用自动回滚的测试隔离交易
相关软件包
- 凯斯利 - 安全型SQL查询构建器
- @geekmidas/ testkit (英语) - 与数据库工厂测试公用事业
许可证
麻省理工学院