初始化数据库连接然后将其附加到插件内的 nitroApp 上下文的概念有意义吗? 用法来自 api/hello ,它执行 { db} = useNitroApp()
这确实有效,我只是想知道这是一件好事还是有更好的事情?(就将数据库附加到 nitroApp 上下文而言) 这是一些测试代码(不安全):
***server/plugins/sql.js
import mysql from 'mysql'
export default defineNitroPlugin((nitro) => {
const con = mysql.createConnection({
host: "127.0.0.1",
user: "users_service",
password: "123",
database: "users"
});
con.connect(function (err) {
if (err) throw err;
console.log("DB Connected!");
nitro.db = con;
});
nitro.hooks.hookOnce("close", async () => {
await new Promise((resolve) => con.end(() => resolve()));
console.log("db connection closed");
});
})
***serve/api/hello.js
export default defineEventHandler(async (event) => {
const { db } = useNitroApp()
const sql = "SELECT * FROM directory";
const directoryData = await new Promise((resolve, reject) => {
db.query(sql, function (err, result) {
if (err) throw err;
resolve(result)
});
})
return directoryData
})
基于此评论,您不应该直接附加到硝基App,而是在钩子请求事件中使用上下文,并在路由API事件中获取它
nuxtApp.hooks.hook("request", e => {e.context.[your attach]});
// or you can use nuxtApp.hooks.hookOnce for attaching it in first request coming
// access it in route
export default defineEventHandler(e => {e.context.[attach]});
如果你使用 useNitroApp() 并解构它,在 npm run build 中,你会看到它给出警告