I want to setup a connection to a PostgreDB in a server plugin so that I can use it whenever needed (I use pg-promise because I find named parameters more convenient).
In ~/server/plugins/connectdb.ts
:
import pgPromise from 'pg-promise'
export default defineNitroPlugin(() => {
console.log('Initializing DB connection')
const pgp = pgPromise({})
try {
const db = pgp('postgres://user:pwd@localhost:5432/mydb')
} catch (error) {
console.error("Error: "+error);
return process.exit(1)
}
})
Then in ~/api/getlist.ts
:
export default defineEventHandler((event) => {
console.log(db);
})
But here db
is unknown. If I run a query just after the initialization, I can see the connection in Postgres' logs. I tried adding:
export let db;
between import
and export default
(and change const db
to let db
in the code) but that doesn't change anything. I guess what I want is kind of a global variable to store the connection.