【问题标题】:Next.js API routes with pg-promiseNext.js API 路由与 pg-promise
【发布时间】:2020-06-06 21:43:19
【问题描述】:

我在 Next.js 应用程序中使用出色的 pg-promise 库与部署在 AWS 上的 Postgres 数据库进行交互。具体来说,我正在使用 API 路由功能,其中/pages/api 中的文件夹映射到相应的端点。这极大地简化了我的代码,并允许我删除自定义的server.js 文件。问题是pg-promise 抛出了这个警告:

WARNING: Creating a duplicate database object for the same connection.

The author has addressed this before,但尽管遵循了建议,但警告仍然存在。

我只初始化一次数据库连接,在database.js:

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

const connection = { ... };

const db = pgp(connection);

module.exports = db;

然后将其传递给我在pages/api 中的API,在本例中为users.js

import db from ‘../database.js;

export default async function handler(req, res) {
  try {
    const users = await db.any('SELECT * FROM table);
    res.json(users)
  } catch (error) {
    res.status(error.status || 500).end(error.message)
  }
}

数据最终会传递给getInitialProps 调用。

是什么导致了警告?在我处理连接对象的过程中是否存在我遗漏的模式或设计缺陷?我已经尝试了各种配置和中间件,但警告仍然存在。

【问题讨论】:

  • 当您收到警告时,它包括调用堆栈,告诉您第二次初始化发生在哪里。照着做就好了。
  • 是的,我忘了说,调用堆栈指向database.js中的原始初始化和users.js中的__webpack_require__,所以指向数据库对象的实际导入。
  • 所以你确实设法执行了两次,通过原始调用,加上通过 webpack 的压缩版本,似乎不知何故。这应该很容易调试并查看调用发生两次的位置。
  • 您找到解决方案了吗?
  • 我有同样的问题,我很惊讶这个库的文档有多差。

标签: javascript node.js pg-promise


【解决方案1】:

通过getStaticProps 函数建立连接。

请参阅以下内容:next/getStaticProps

您必须在此函数中导入 pg-promise 库,就像在 express 等服务器框架中一样。

【讨论】:

    【解决方案2】:

    我认为您可以使用本教程中的noWarnings: truehttps://techsolutionshere.com/next-js-with-postgresql/

    const pgp = require('pg-promise')({
        noWarnings: true
    })
    
    const db = pgp(`postgres://User:Password@localhost:5432/product-test`)
    
    
    export default async (req, res) => {
        try {
            const { name, price,  imageUrl, description } = req.query
    
            if(!name || !price || !imageUrl || !description){
                return res.status(422).send({error: ['Missing one or more fields']})
            }
    
            const product = await db.one('INSERT INTO products(name, price, imageUrl, description) VALUES($1, $2, $3, $4) RETURNING *', [name, price, imageUrl, description])
    
            res.status(200).json(product)
    
        } catch (error) {
            // console.error(error);
            res.status(500).send({message: ["Error creating on the server"], error: error})
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-12
      • 2021-11-18
      • 2021-06-21
      • 2021-08-12
      • 2021-12-09
      • 2019-12-22
      • 2021-12-17
      • 1970-01-01
      相关资源
      最近更新 更多