【问题标题】:Should I release client in Knex.js?我应该在 Knex.js 中发布客户端吗?
【发布时间】:2021-06-26 12:33:17
【问题描述】:

我将 PostgreSQL 与 pg 一起使用。配置如下:

const { Pool } = require("pg");
const { dbUser, dbHost, database, dbHmac, dbPort } = require("../config");

const dbConfig = {
  user: dbUser,
  host: dbHost,
  database,
  password: dbHmac,
  port: dbPort,
  max: 10,
  idleTimeoutMillis: 30000
 };

 var pool = new Pool(dbConfig);
 module.exports = pool;

目前池的使用如下:

app.post("/deleteCognitoUserBasedOnEmail", async function (req, res) {
let isUserAdminRes, email = req.body.email;
try {
   isUserAdminRes = await client.query(
   `select is_admin from end_user where email = $1`,[email]
   );
}
catch (e) {
  client.release();
  console.error("Error occurred : " + e);
  return res.status(500).send({ errorMessage: "Internal Server Error. " + e.message });
}
client.release();
return res
  .status(status)
  .send({ responseMessage });
 }

正如大家所见,我必须在任何地方释放客户端。我的项目中有一些复杂的函数将客户端作为参数传递。这种方式有时跟踪客户变得困难。我决定切换到 knex.js。 Knex.js 中有这样的限制吗?我阅读了 knex.js 中的 .destroy() 方法,但是当您不需要连接时使用它。但在我的项目中,API 会在一天中被多次访问。

【问题讨论】:

  • 不,knex.js 为您管理池 - 它借用客户端进行查询并自动释放它。如果你使用交易,你只需要确保你解决了你的承诺。
  • @RobertKawecki 感谢您的回复。你能把我提到的官方文件里说的一样吗?
  • @RobertKawecki 非常感谢。
  • 我已将我的评论提升为答案,因为它比我最初设想的涉及更多。还使链接永久化(指向特定的 git 修订版)。

标签: node.js postgresql knex.js


【解决方案1】:

对于knex.js,众多的例子都省略了连接管理;它在用户代码中不存在。它只是没有在文档中提到,因为你不这样做。因此,它由缺席记录

如果您更喜欢确凿证据,这里是在 knex.js 中实际执行查询的代码 - 请注意 ensureConnection 在查询之前如何建立连接并在查询之后释放它:https://github.com/knex/knex/blob/8cfad286f246aff7455784b51751fdd17ba24c4c/lib/execution/runner.js#L27

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-13
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    相关资源
    最近更新 更多