我应该在哪里初始化pg-promise [英] Where should I initialize pg-promise

查看:187
本文介绍了我应该在哪里初始化pg-promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习 nodejs-postgres 并找到了 pg-promise 包。
我阅读了文档和示例,但我不明白我应该在哪里放置初始化代码?我使用Express,我有很多路线。

I just started to learn nodejs-postgres and found the pg-promise package. I read the docs and examples but I don't understand where should I put the initialization code? I using Express and I have many routes.

我必须将整个初始化(包括 pg-monitor init)放到我想要的每个文件中查询数据库或我需要包含和 initalize / configure 它们只在server.js中?

I have to put whole initialization (including pg-monitor init) to every single file where I would like to query the db or I need to include and initalize/configure them only in the server.js?

如果我只在server.js中初始化它们应该包含哪些我需要db查询的文件?

If I initialized them only in the server.js what should I include other files where I need a db query?

换句话说。我不清楚pg-promise和pg-monitor 配置/初始化是全局还是本地行动?

In other words. Its not clear to me if pg-promise and pg-monitor configuration/initalization was a global or a local action?

我还不清楚是否需要为每个查询创建一个db变量并结束pgp?

It's also unclear if I need to create a db variable and end pgp for every single query?

var db = pgp(connection);

db.query(...).then(...).catch(...).finally(**pgp.end**);


推荐答案

您只需要初始化数据库连接一次。如果要在模块之间共享,则将其放入自己的模块文件中,如下所示:

You need to initialize the database connection only once. If it is to be shared between modules, then put it into its own module file, like this:

const initOptions = {
    // initialization options;
};

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

const cn = 'postgres://username:password@host:port/database';
const db = pgp(cn);

module.exports = {
    pgp, db
};

参见支持的初始化选项

更新

如果您尝试使用相同的连接详细信息创建多个数据库对象,则库将向控制台输出警告:

And if you try creating more than one database object with the same connection details, the library will output a warning into the console:

警告:为同一连接创建重复的数据库对象。对象
。< anonymous> (D:\NodeJS \tests\test2.js:14:6)

这指出你的数据库使用模式很糟糕,即你应该共享数据库对象,如上所示,而不是重新创建它。从版本6.x开始,它变得至关重要,每个数据库对象都维护着自己的连接池,因此重复这些将导致连接使用率不佳。

This points out that your database usage pattern is bad, i.e. you should share the database object, as shown above, not re-create it all over again. And since version 6.x it became critical, with each database object maintaining its own connection pool, so duplicating those will additionally result in poor connection usage.

此外,没有必要导出 pgp - 初始化的库实例。相反,您可以这样做:

Also, it is not necessary to export pgp - initialized library instance. Instead, you can just do:

module.exports = db;

如果在某个模块中你需要使用库的根,你可以通过属性 $ config :

And if in some module you need to use the library's root, you can access it via property $config:

const db = require('../db'); // your db module
const pgp = db.$config.pgp; // the library's root after initialization

这篇关于我应该在哪里初始化pg-promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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