启动应用程序时,使用pg-promise验证数据库连接 [英] Verify database connection with pg-promise when starting an app

查看:676
本文介绍了启动应用程序时,使用pg-promise验证数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个使用 pg-promise 模块连接到postgres数据库的快速应用程序。 p>

我想确保启动应用服务器时数据库连接成功。换句话说,如果与数据库的连接失败,我想抛出一个错误。



我的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}`);
});

当前的配置将启动快速服务器无论是否数据库连接是有效的,这不是我想要的行为。



我尝试浏览文档,但找不到解决方案。我也试过 const db = pgp(databaseConfig).catch((err)=> {// blow up}); ,但是没有工作,因为 pgp 不返回承诺。

解决方案

我是 pg-promise ;)这不是第一次提出这个问题,所以我在这里给出详细的解释。



当您实例化一个新的数据库对象,如下所示:

  const db = pgp(connection); 

...所有它 - 创建对象,但不尝试连接。库建立在连接池之上,只有实际的查询方法从池中请求一个连接。



从官方文档


对象 db 表示数据库协议,具有懒惰数据库连接,即只有实际的查询方法获取并释放连接。因此,您应该为每个连接详细信息创建一个全局/共享 db 对象。


但是,您可以通过使用方法 connect ,如下所示。



虽然此方法不再是链接查询的推荐方式,但自从支持任务(作为更安全的方法),它一般来说,仍然可以方便地检查连接。



我从我自己的帖子中复制了示例: https://github.com/vitaly-t/pg-promise/issues/81



以下是以两种方式同时进行的一个例子,所以你可以选择任何一种方法ou喜欢更好。

  const initOptions = {
//全局事件通知;
error:(error,e)=> {
if(e.cn){
//连接相关的错误;
//
//连接报告回密码散列,
//用于安全错误日志记录,而不会泄露密码。
console.log('CN:',e.cn);
console.log('EVENT:',error.message || error);
}
}
};

const pgp = require('pg-promise')(initOptions);

//使用无效的连接字符串:
const db = pgp('postgresql:// userName:password @ host:port / database');

db.connect()
.then(obj => {
obj.done(); //成功,释放连接;
})
.catch(error => {
console.log('ERROR:',error.message || error);
});

输出:



CN:postgresql:// userName:########主机:port / database
EVENT:getaddrinfo ENOTFOUND主机主机:5432
错误:getaddrinfo ENOTFOUND主机主机:5432



库中的每个错误首先通过全局错误事件处理程序,只有在相应的 .catch 处理程序。



替代方案



而不是手动建立连接,您可以简单地执行一种查询类型,总是成功地进行有效的连接,如下所示:

  db.proc('version')
。 (data => {
// SUCCESS
// data.version =
//'PostgreSQL 9.5.1,由Visual C ++ build 1800编译,64位'
})
.catch(error => {
// connection-related error
});

API链接:




I am building an express application that connects to a postgres database using the pg-promise module.

I would like to ensure that the database connection is successful when starting the application server. In other words, if the connection to the database fails, I'd like to throw an error.

My server.js file is as follows:

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}`);
});

The current configuration will start the express server regardless of whether the database connection is valid, which is not the behavior I would like.

I tried browsing the docs but couldn't find a solution. I also tried const db = pgp(databaseConfig).catch((err) => { // blow up });, but that didn't work because pgp does not return a promise.

解决方案

I am the author of pg-promise ;) And this isn't the first time this question is asked, so I'm giving it a detailed explanation here.

When you instantiate a new database object like this:

const db = pgp(connection);

...all it does - creates the object, but it does not try to connect. The library is built on top of the connection pool, and only the actual query methods request a connection from the pool.

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.

However, you can ask the library to connect without executing any query, by using method connect, as shown further.

And while this method is no longer a recommended way for chaining queries, ever since support for Tasks has been introduced (as a safer approach), it still comes in handy checking for the connection in general.

I copied the example from my own post: https://github.com/vitaly-t/pg-promise/issues/81

Below is an example of doing it in two ways at the same time, so you can choose whichever approach you like better.

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 => {
        obj.done(); // success, release the connection;
    })
    .catch(error => {
        console.log('ERROR:', error.message || error);
    });

Outputs:

CN: postgresql://userName:########@host:port/database EVENT: getaddrinfo ENOTFOUND host host:5432 ERROR: getaddrinfo ENOTFOUND host host:5432

Every error in the library is first reported through the global error event handler, and only then the error is reported within the corresponding .catch handler.

Alternative

Instead of establishing the connection manually, you can simply execute a type of query that would always succeed for a valid connection, like the following one:

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 links:

这篇关于启动应用程序时,使用pg-promise验证数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆