简体   繁体   English

Next.js API 条带有 pg-promise 的路由

[英]Next.js API routes with pg-promise

I'm using the excellent pg-promise library inside a Next.js app to interface with a Postgres database deployed on AWS.我在 Next.js 应用程序中使用优秀的pg-promise库来连接部署在 AWS 上的 Postgres 数据库。 Specifically, I'm using the API routes feature, where folders inside /pages/api are mapped to corresponding endpoints.具体来说,我正在使用 API 路由功能,其中/pages/api中的文件夹映射到相应的端点。 This has vastly simplified my code and allowed me to remove a custom server.js file.这极大地简化了我的代码并允许我删除自定义server.js文件。 The problem is that pg-promise throws this warning:问题是pg-promise抛出这个警告:

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

The author has addressed this before , but despite following the advice, the warning persists. 作者之前已经解决过这个问题,但是尽管听从了建议,警告仍然存在。

I initialize the database connection only once, in database.js :我只在database.js中初始化数据库连接一次:

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

const connection = { ... };

const db = pgp(connection);

module.exports = db;

And then pass it along to my APIs in pages/api , in this case, users.js :然后将其传递到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)
  }
}

The data eventually makes its way to a getInitialProps call.数据最终进入getInitialProps调用。

What is causing the warning?是什么导致了警告? Is there a pattern I'm missing or a design flaw in my handling of the connection object?在处理连接 object 时是否存在我遗漏的模式或设计缺陷? I've experimented with various configs and middlewares, but the warning remains.我尝试了各种配置和中间件,但警告仍然存在。

Establishing a connection is made via the getStaticProps function.通过getStaticProps function 建立连接。

see the following: next/getStaticProps请参阅以下内容: next/getStaticProps

You must import the pg-promise library within this function, just as you would within a server framework like express.您必须在这个 function 中导入 pg-promise 库,就像在 express 这样的服务器框架中一样。

I think you can use noWarnings: true as from this tutorial: https://techsolutionshere.com/next.js-with-postgresql/我认为您可以使用noWarnings: true从本教程开始: https://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})
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM