在其他Node.js文件中重复使用PostgreSQL连接池

5
我正在创建基于Node.js后端应用并使用PostgreSQL数据库。我的目标是在db.js文件中创建数据库连接后,可以在其他文件中重复利用该连接以执行查询。
以下是我的db.js文件:
const pool = new Pool({
    user: 'us',
    host: 'localhost',
    database: 'db',
    password: 'pass',
    port: 5432,
})
pool.on('connect', () => {
    console.log('connected to the Database');
});
module.exports = () => { return pool; }

这是我在 index.js 文件中尝试使用它的方式:

const db = require('./db.js')

app.get('/', (request, response) => {

    db().query('SELECT * FROM country'), (error, results) => {
        if (error) {
            response.send(error)
        }
        console.log(results)
        response.status(201).send(results)
    }
})

页面没有错误,但是当我访问这个特定的页面时,它会一直加载,控制台也没有任何显示。

但是,如果我在我的db.js文件中编写一个函数并执行像pool.query(...)这样的操作,然后导出该函数,在我的index.js中编写app.get('/', exportedFunction),那么一切都能正常工作。

有没有办法不把所有的(大约50个)查询都写在同一个(db.js)文件中,因为我想对我的项目进行一些组织?


请问你能分享一下在 db.js 文件里编写的函数吗? - Subbu
1个回答

3

为了彻底精简项目结构,如果你是从零开始的话,可以尝试以下步骤:

index.js

const express = require('express');
const app = express();

const PORT = 8080;
const bodyparser = require('body-parser');
const baseRouter = require('../your-router');

app.use(bodyparser.json());
app.use(express.json());
app.use('/', baseRouter);

app.listen(PORT, function () {
console.log('Server is running on PORT:', PORT);
}); 

your-router.js

const Router = require('express');
const router = Router();
const getCountries = require('../handlers/get');

router.get('/check-live', (req, res) => res.sendStatus(200));
// route for getCountries
router.get('/countries', getCountries);

src/handler/get.js

const YourService = require('./service/your-service');

function getCountries(request, response) {
    const yourService = new YourService();
    yourService.getCountries(request)
        .then((res) => { response.send(res); })
        .catch((error) => { response.status(400).send({ message: error.message }) })
}

module.exports = getCountries;

src/service/your-service.js

const connectionPool = require('../util/dbConnect');
class yourService {

    getCountries(req) {
        return new Promise(((resolve, reject) => {
            connectionPool.connect((err, db) => {
                if (err) reject(err);
                let query = format('SELECT * FROM country'); // get inputs from req
                db.query(query, (err, result) => {
                    if (err) reject(err);
                    resolve(result);
                })
            });
        }));
    }
}

module.exports = yourService;

dbConnect.js

const pgCon = require('pg')
const PGUSER = 'USER'
const PGDATABASE = 'localhost'
let config = {
    user: PGUSER,
    database: PGDATABASE,
    max: 10,
    idleTimeoutMillis: 30000
}

let connectionPool = new pgCon.Pool(config);

module.exports = connectionPool;

请将代码重构为使用回调/异步等待的示例(在上面的示例中,您只需使用回调而不需要转换为Promise),如果需要-您可以从服务层进行DB层调用以从服务层中提取DB方法。

2
谢谢,这很有帮助,特别是dbConnect.js和your-service.js,我在其中找到了如何导出创建的池并在另一个文件中使用它的方法,这是我的主要问题。还要感谢您提供整个项目结构示例! - lexus_sa
"const yourService = new YourService();" 给我一个 "YourService 不是构造函数" 的错误,这是为什么? - vikrant
你还没有在 Promise 中使用 resolve 函数,那么 "then" 如何在 Promise 中工作呢? - vikrant
@vikrant:这是一个基本的代码,更多地展示了结构,而不是实际编码!因此,一旦.connect被返回,连接就会被释放,并且可以重新使用。如果你正在查看代码,请尝试使用更新后的答案。 - whoami - fakeFaceTrueSoul
但是关于“类不是构造函数”的错误呢? - vikrant
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接