user1088963
user1088963

Reputation: 237

Nitro DB initialization pattern using plugin, does this make sense? (nuxt, mysql)

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
})

Upvotes: 4

Views: 1425

Answers (2)

mohamed-mhiri
mohamed-mhiri

Reputation: 232

Another option to consider: use Nitro Utils

// nitro.config.ts

export default defineNitroConfig({

  runtimeConfig: {

    mongodb: {

      uri: 'mongodb://localhost:27017',

      database: 'dbname',

    }

  }

});



// server/utils/mongodb.ts

An other option to consider is using Nitro utils

import { MongoClient } from 'mongodb';



let client: MongoClient;

let clientPromise: Promise<MongoClient>;



const uri = useRuntimeConfig().mongodb.uri;



if (clientPromise === undefined) {  

  client = new MongoClient(uri);

  clientPromise = client.connect();

}



export const getDatabase = async () => {

  const client = await clientPromise;

  return client.db(useRuntimeConfig().mongodb.database);

}



// server/api/lectures

import { getDatabase } from '~/server/utils/mongodb';



export default defineEventHandler(async (event) => {

  try {

    const database = await getDatabase();

    const lectures = database.collection('lectures');

    

    const query = {};

    const cursor = lectures.find(query);

    const result = await cursor.toArray();

    

    return result;

  } catch (e) {

    console.error(e)

    throw createError({

      statusCode: 500,

      message: 'Database error'

    });

  }

})

Upvotes: 0

Iqro Negoro
Iqro Negoro

Reputation: 1

Based on this comment, you should not attach directly to nitroApp, but using context in hooks request event, and get it in route API event

nuxtApp.hooks.hook("request", e => {e.context.[your attach]});

// access it in route
export default defineEventHandler(e => {e.context.[attach]});

if you using useNitroApp() and destructure it, at npm run build, you will see its giving a warning

Upvotes: 0

Related Questions