@geekmidas/db

中文文档
9.6.1发布于 2026/11/16TypeScriptESM + CJS构建来源已验证近 30 天下载 1.5万

为Kysely提供灵活的交易管理的数据库服务。 提供帮助者以类型安全的方式处理数据库连接和交易.

中文使用文档
文档目录21 节
  1. 特征
  2. 安装
  3. 同伴依赖关系
  4. 快速启动
  5. API 参考
  6. withTransaction
  7. DatabaseConnection<T>
  8. 用法实例
  9. 基本交易
  10. 嵌入式交易
  11. 仓库模式
  12. 有交易的服务模式
  13. 处理错误
  14. 用交易测试
  15. 类型安全
  16. 高级图案
  17. 工作模式股
  18. 连接集合
  19. 最佳做法
  20. 相关软件包
  21. 许可证

@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();
    }
  });
}

最佳做法

  1. 使用数据库连接类型: 接受 DatabaseConnection 与交易有关的职能

    async function myFunction(db: DatabaseConnection<Database>) { }
    
  2. 让交易处理重用: 不要手动检查交易类型

    // Good
    await withTransaction(db, async (trx) => { });
    
    // Avoid
    if (db.isTransaction) { /* ... */ } else { /* ... */ }
    
  3. 保持交易简短: 迅速执行以避免阻塞

    // 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!
    });
    
  4. 处理错误: 让交易自动滚回错误

  5. 测试: 使用自动回滚的测试隔离交易

许可证

麻省理工学院

版本与发布记录

@geekmidas/db 共发布 206 个版本,首次发布于 2025/10/01;过去 12 个月发布了 202 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
9.6.1latest2026/11/16今天
10.0.0-alpha.185alpha2026/11/16今天
10.0.0-alpha.1842026/11/16今天
10.0.0-alpha.1832026/11/16今天
10.0.0-alpha.1822026/11/132 天前
10.0.0-alpha.1812026/11/133 天前

关于 @geekmidas/db 的常见问题

@geekmidas/db 是什么?

为Kysely提供灵活的交易管理的数据库服务。 提供帮助者以类型安全的方式处理数据库连接和交易.

如何安装 @geekmidas/db?

在项目目录运行 npm install @geekmidas/db,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:pg(~8.16.3)、knex(~3.1.0)、kysely(>=0.28.2 <0.30.0)、vitest(^3.2.4 || ^4.1.11)、db-errors(~0.2.3)、objection(~3.1.5)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@geekmidas/db 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@geekmidas/db 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@geekmidas/db 可以商用吗?

@geekmidas/db 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@geekmidas/db 的下载量有多少?

根据 npm 官方下载统计,@geekmidas/db 在 2026/10/16 – 2026/11/14 这 30 天内被下载 14,541 次,日均约 485 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@geekmidas/db 还在维护吗?

最新版本 9.6.1 发布于 2026/11/16(今天);至今共发布 206 个版本,其中过去 12 个月发布了 202 个;首次发布于 2025/10/01。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。