0

does the concept of initing a db connection then attaching it to the nitroApp context within a plugin make sense? usage is from api/hello and that does a { db} = useNitroApp()

this does work, im just wondering if this is a good thing to do or is there something better?(in terms of attaching db to the nitroApp context) this is some test code(ino its no secure):

***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
})
user1088963
  • 197
  • 1
  • 14

0 Answers0