pg-promise如何处理同一个应用程序中的多个客户端

时间:2018-06-04 13:56:10

标签: node.js postgresql pg pg-promise

我只使用pg模块创建代码,其中我有一个执行查询的常规函数​​。如果客户端不将现有客户端作为参数,则可以在现场创建客户端。或者它可以使用现有的客户端来执行查询。所以我可以调用这个函数,如(伪代码)

const {Client} = require('pg');

const clientobj = {user:...}

generalQuery(text, params, client){
  if !client{client = new Client(clientobj);}
  client.query(text , params)
  client.end();
  else
  client = client
  client.query(text , params)
  return query results
}

call like 
generalQuery(text, params, false)

or via another function that already created a client

anotherFunction(){
  client = new Client(clientobj);
  client.query(insert)...
  do some things with the results
  generalQuery(text, params, client)
  do some things with the results
  now client.end();
}
exports.anotherFunction= anotherFunction;
exports.generalQuery= generalQuery;

所以,如果我有一个已经创建的客户端,我不需要在generalQuery中创建另一个客户端,只有在anotherFunction中返回结果后才会断开客户端。另外,我可以按原样拨打generalQuery""我想要随时随地处理其余的事情。

pg-promise如何处理?除特殊情况外,一般来说,它不会暴露client

所以我想我必须重构我的代码并拥有一个通用查询功能,它将始终在内部处理客户端连接和断开连接,并且永远不会在已有的客户端上调用此函数。伪代码

const pgp = require('pg-promise')();
const db = pgp(connection);

generalQuery(text, params){
   db.any(text, params)//all client connection/disconnection is handled here
    .then(function(data) {
        // success;
    })
    .catch(function(error) {
        // error;
    });
}

call like 
generalQuery(text, params)

or via another function that never has an already created client

anotherFunction(){
  generalQuery(text, params)
  do some things with the results
  generalQuery(text, params)
  do some things with the results
}
exports.anotherFunction= anotherFunction;
exports.generalQuery= generalQuery; 

因此,使用pg-promise,不需要拥有我的第一个示例的逻辑,只有通用查询函数创建和处理连接。这是否意味着它还会自动处理断线?如果我做错了什么或者我错过了重要的事情,请提供建议。

谢谢

0 个答案:

没有答案