启动应用程序时使用 pg-promise 验证数据库连接
Verify database connection with pg-promise when starting an app
我正在构建一个使用 pg-promise 模块连接到 postgres 数据库的快速应用程序。
我想确保启动应用服务器时数据库连接成功。换句话说,如果与数据库的连接失败,我想抛出一个错误。
我的server.js文件如下:
const express = require("express");
const databaseConfig= {
"host": "localhost",
"port": 5432,
"database": "library_app",
"user": "postgres"
};
const pgp = require("pg-promise")({});
const db = pgp(databaseConfig);
const app = express();
const port = 5000;
app.listen(port, (err) => {
console.log(`running server on port: ${port}`);
});
当前配置将启动 express 服务器不管数据库连接是否有效,这不是我想要的行为。
我尝试浏览文档但找不到解决方案。我也试过了
const db = pgp(databaseConfig).catch((err) => { // blow up });
但这没有用,因为 pgp
没有 return 承诺。
我是pg-promise的作者;)而且这不是第一次有人问这个问题,所以我在这里给它一个详细的解释。
当您像这样实例化一个新的数据库对象时:
const db = pgp(connection);
...它所做的一切 - 创建对象,但它不会尝试连接。该库建立在连接池之上,只有实际的查询方法才从池中请求连接。
From the official documentation:
Object db
represents the database protocol, with lazy database connection, i.e. only the actual query methods acquire and release the connection. Therefore, you should create only one global/shared db
object per connection details.
但是,您可以强制连接,通过调用方法 connect, as shown further. And while this method is not a recommended way for chaining queries (Tasks 应该用于此),它通常可以方便地检查连接。
我从自己的 post 复制了示例:https://github.com/vitaly-t/pg-promise/issues/81
以下是同时以两种方式进行的示例,因此您可以选择更喜欢的方式。
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:password@host:port/database');
db.connect()
.then(obj => {
// Can check the server version here (pg-promise v10.1.0+):
const serverVersion = obj.client.serverVersion;
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
处理程序中报告错误。
更新
测试连接的现代方法 + 一步获取服务器版本:
// tests connection and returns Postgres server version,
// if successful; or else rejects with connection error:
async function testConnection() {
const c = await db.connect(); // try to connect
c.done(); // success, release connection
return c.client.serverVersion; // return server version
}
链接
作为替代方案,在我升级 pg-promise 包之前,none 对我有用
我正在构建一个使用 pg-promise 模块连接到 postgres 数据库的快速应用程序。
我想确保启动应用服务器时数据库连接成功。换句话说,如果与数据库的连接失败,我想抛出一个错误。
我的server.js文件如下:
const express = require("express");
const databaseConfig= {
"host": "localhost",
"port": 5432,
"database": "library_app",
"user": "postgres"
};
const pgp = require("pg-promise")({});
const db = pgp(databaseConfig);
const app = express();
const port = 5000;
app.listen(port, (err) => {
console.log(`running server on port: ${port}`);
});
当前配置将启动 express 服务器不管数据库连接是否有效,这不是我想要的行为。
我尝试浏览文档但找不到解决方案。我也试过了
const db = pgp(databaseConfig).catch((err) => { // blow up });
但这没有用,因为 pgp
没有 return 承诺。
我是pg-promise的作者;)而且这不是第一次有人问这个问题,所以我在这里给它一个详细的解释。
当您像这样实例化一个新的数据库对象时:
const db = pgp(connection);
...它所做的一切 - 创建对象,但它不会尝试连接。该库建立在连接池之上,只有实际的查询方法才从池中请求连接。
From the official documentation:
Object
db
represents the database protocol, with lazy database connection, i.e. only the actual query methods acquire and release the connection. Therefore, you should create only one global/shareddb
object per connection details.
但是,您可以强制连接,通过调用方法 connect, as shown further. And while this method is not a recommended way for chaining queries (Tasks 应该用于此),它通常可以方便地检查连接。
我从自己的 post 复制了示例:https://github.com/vitaly-t/pg-promise/issues/81
以下是同时以两种方式进行的示例,因此您可以选择更喜欢的方式。
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:password@host:port/database');
db.connect()
.then(obj => {
// Can check the server version here (pg-promise v10.1.0+):
const serverVersion = obj.client.serverVersion;
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
处理程序中报告错误。
更新
测试连接的现代方法 + 一步获取服务器版本:
// tests connection and returns Postgres server version,
// if successful; or else rejects with connection error:
async function testConnection() {
const c = await db.connect(); // try to connect
c.done(); // success, release connection
return c.client.serverVersion; // return server version
}
链接
作为替代方案,在我升级 pg-promise 包之前,none 对我有用