我想在我的主index.js中优雅地停止process.on('SIGINT', handler)
上的postgres数据库。
使用Node Postgres,我正在使用一个包含4个客户端的池。在阅读了标题为shut it down的文档以关闭池之后,我需要先发布客户端。
从导出的pool
本身(module.exports.pool = pool;
)
,如何访问池中的客户端来执行此操作?这就是我启动postgres db,创建池并将其导出到其他模块的方法。
const colors = require('colors');
const pg = require('pg');
if (process.env.DOLPHIN_TEST) {
var dbName = 'test_dolphin_db';
var maxCon = 1
} else {
var dbName = 'dev_dolphin_db';
var maxCon = 4
}
const config = {
user: 'postgres',
database: dbName,
host: 'localhost',
max: maxCon,
idleTimeoutMillis: 30000
}
const pool = new pg.Pool(config);
function poolConnected(err, client, done, resolve) {
if(err) {
return promiseArgs.reject(`error fetching client from pool ${err}`);
}
client.query('SELECT $1::int AS number', ['1'], function(err, result) {
//call `done()` to release the client back to the pool
done();
if(err) {
return console.error('error running query', err);
}
console.log(colors.grey(
`Postgres is online using ${client.database} as user ${client.user}\n` +
`and is listening on ${client.host}`));
promiseArgs.resolve();
});
}
var promiseArgs = { resolve: undefined, reject: undefined };
function initDb() {
var promise = new Promise(function(resolve, reject) {
promiseArgs.resolve = resolve;
promiseArgs.reject = reject;
pool.connect(poolConnected);
pool.on('error', function (err, client) {
// if an error is encountered by a client while it sits idle in the pool
// the pool itself will emit an error event with both the error and
// the client which emitted the original error
// this is a rare occurrence but can happen if there is a network partition
// between your application and the database, the database restarts, etc.
// and so you might want to handle it and at least log it out
console.error('idle client error', err.message, err.stack)
});
});
return promise;
}
module.exports.pool = pool;
module.exports.initDb = initDb;