簡體   English   中英

Next.js API 條帶有 pg-promise 的路由

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

我在 Next.js 應用程序中使用優秀的pg-promise庫來連接部署在 AWS 上的 Postgres 數據庫。 具體來說,我正在使用 API 路由功能,其中/pages/api中的文件夾映射到相應的端點。 這極大地簡化了我的代碼並允許我刪除自定義server.js文件。 問題是pg-promise拋出這個警告:

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

作者之前已經解決過這個問題,但是盡管聽從了建議,警告仍然存在。

我只在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調用。

是什么導致了警告? 在處理連接 object 時是否存在我遺漏的模式或設計缺陷? 我嘗試了各種配置和中間件,但警告仍然存在。

通過getStaticProps function 建立連接。

請參閱以下內容: next/getStaticProps

您必須在這個 function 中導入 pg-promise 庫,就像在 express 這樣的服務器框架中一樣。

我認為您可以使用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