私はpg-promiseの著者です;)これは初めてこの質問がされたわけではありませんので、ここで詳しく説明します。
あなたはこのような新しいデータベースオブジェクトインスタンス化:
const db = pgp(connection);
を...それがないすべて - オブジェクトを作成し、それが接続しようとしません。ライブラリは接続プールの上に構築され、実際のクエリメソッドだけがプールからの接続を要求します。
From the official documentation:
オブジェクトdb
、すなわちのみ実際のクエリ方法を取得して接続を解放し、怠惰なデータベース接続と、データベース・プロトコルを表します。したがって、接続の詳細ごとに1つのグローバル/共有db
オブジェクトを作成する必要があります。
ただし、図に示すように、connectメソッドを使用して、クエリを実行せずに接続するようにライブラリに依頼することができます。
Tasksのサポートが(より安全なアプローチとして)導入されて以来、これはもはや接続を一般的に便利にチェックしています。
私は自分のポストから例をコピー:あなたはより良い好きな方アプローチを選択することができますので、以下https://github.com/vitaly-t/pg-promise/issues/81
は、同時に2つの方法でそれをやった例です。
const initOptions = {
// global event notification;
error: (error, e) => {
if (e.cn) {
// A connection-related error;
//
// Connections are reported back with the password hashed,
// for safe errors logging, without exposing passwords.
console.log('CN:', e.cn);
console.log('EVENT:', error.message || error);
}
}
};
const pgp = require('pg-promise')(initOptions);
// using an invalid connection string:
const db = pgp('postgresql://userName:[email protected]:port/database');
db.connect()
.then(obj => {
obj.done(); // success, release the connection;
})
.catch(error => {
console.log('ERROR:', error.message || error);
});
出力:
CN: postgresql://userName:########@host:port/database EVENT: getaddrinfo ENOTFOUND host host:5432 ERROR: getaddrinfo ENOTFOUND host host:5432
すべてのエラーライブラリーでは、最初のグローバルerrorイベントハンドラによって報告され、その後にのみエラーが対応する.catch
ハンドラ内で報告されます。
db.proc('version')
.then(data => {
// SUCCESS
// data.version =
// 'PostgreSQL 9.5.1, compiled by Visual C++ build 1800, 64-bit'
})
.catch(error => {
// connection-related error
});
APIリンク:代わりに手動で接続を確立する
代替
は、単に1次のように、常に有効な接続のために成功するクエリの種類を実行することができ
それは、ここに答えた:https://github.com/vitaly-t/pg-promise/issues/81 –