[英]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.