You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将下述Knex数据库连接实现为等价DB类?求示例实现

将Knex连接封装为DB类的实现

下面是把你提供的Knex连接逻辑封装成DB类的等价实现,用单例模式确保全局只有一个连接池实例:

const knex = require('knex');

class DB {
  // 单例实例
  static #instance;

  // 私有构造函数,防止外部直接new
  constructor() {
    this.knexInstance = knex({
      client: 'pg',
      connection: {
        host: '127.0.0.1',
        user: 'your_database_user',
        password: 'your_database_password',
        database: 'myapp_test'
      },
      pool: { min: 0, max: 7 }
    });
  }

  // 获取单例实例
  static getInstance() {
    if (!DB.#instance) {
      DB.#instance = new DB();
    }
    return DB.#instance;
  }

  // 封装常用查询方法,也可以直接暴露knexInstance使用原生API
  async query(sql, bindings) {
    return this.knexInstance.raw(sql, bindings);
  }

  // 关闭连接池
  async close() {
    await this.knexInstance.destroy();
    DB.#instance = null; // 重置实例,方便后续重新初始化
  }

  // 直接暴露knex实例,支持所有Knex原生操作
  get knex() {
    return this.knexInstance;
  }
}

module.exports = DB;

使用示例

// 获取DB实例
const db = DB.getInstance();

// 执行原生SQL查询
const result = await db.query('SELECT * FROM users WHERE id = ?', [1]);

// 使用Knex链式查询
const users = await db.knex('users').where('active', true).select('*');

// 关闭连接池(比如应用退出时)
await db.close();

关键点说明

  • 用单例模式避免重复创建连接池,节省资源
  • 私有构造函数确保只能通过getInstance获取实例
  • 既封装了简化的query方法,也通过knex属性暴露完整的Knex API,兼顾易用性和灵活性
  • 提供close方法用于主动销毁连接池,适合应用 shutdown 场景

内容的提问来源于stack exchange,提问作者ahmad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 12:45:49