11import { createDatabase } from 'db0'
2+ import type { Database } from 'db0'
23import type { ModuleOptions } from 'nuxt-users/utils'
34
5+ const dbCache = new Map < string , Database > ( )
6+
7+ export const closeAllDbConnections = async ( ) => {
8+ for ( const db of dbCache . values ( ) ) {
9+ if ( db && typeof ( db as any ) . disconnect === 'function' ) {
10+ await ( db as any ) . disconnect ( )
11+ }
12+ }
13+ dbCache . clear ( )
14+ }
15+
416export const getConnector = async ( name : string ) => {
517 try {
618 switch ( name ) {
@@ -17,15 +29,21 @@ export const getConnector = async (name: string) => {
1729 catch ( error ) {
1830 if ( error instanceof Error && error . message . includes ( 'Cannot resolve' ) ) {
1931 throw new Error ( `Database connector "${ name } " not found. Please install the required peer dependency:\n`
20- + '- For sqlite: yarn add better-sqlite3\n'
21- + '- For mysql: yarn add mysql2\n'
32+ + '- For sqlite: yarn add better-sqlite3\n'
33+ + '- For mysql: yarn add mysql2\n'
2234 + '- For postgresql: yarn add pg' )
2335 }
2436 throw error
2537 }
2638}
2739
28- export const useDb = async ( options : ModuleOptions ) => {
40+ export const useDb = async ( options : ModuleOptions ) : Promise < Database > => {
41+ const cacheKey = JSON . stringify ( options . connector )
42+
43+ if ( dbCache . has ( cacheKey ) ) {
44+ return dbCache . get ( cacheKey ) !
45+ }
46+
2947 const connectorName = options . connector ! . name
3048 const connector = await getConnector ( connectorName )
3149
@@ -36,7 +54,9 @@ export const useDb = async (options: ModuleOptions) => {
3654 }
3755
3856 try {
39- return createDatabase ( connector ( connectorOptions ) )
57+ const db = createDatabase ( connector ( connectorOptions ) )
58+ dbCache . set ( cacheKey , db )
59+ return db
4060 }
4161 catch ( error ) {
4262 console . warn ( `[Nuxt Users] ⚠️ Failed to connect to ${ connectorName } database:` , error instanceof Error ? error . message : 'Unknown error' )
@@ -54,4 +74,4 @@ export const checkTableExists = async (options: ModuleOptions, tableName: string
5474 // Table doesn't exist or connection failed
5575 return false
5676 }
57- }
77+ }
0 commit comments