11import updateDotenv from 'update-dotenv' ;
22import logger from './services/logger.js' ;
3- import mongoose , { mongo , Schema } from 'mongoose' ;
3+ import mongoose , { Schema } from 'mongoose' ;
44import util from 'util' ;
5- import { da } from 'date-fns/locale' ;
65
76class Database {
87 mongoose : mongoose . Mongoose | null = null ;
9- mongodbUri : string ;
8+ mongodbUri ? : string ;
109
11- constructor ( mongodbUri : string ) {
12- this . mongodbUri = mongodbUri ;
13- }
14-
15- async connect ( ) {
16- //improve the logger message @12:12
10+ constructor ( ) { }
1711
18- logger . info ( 'Connecting to the database' , this . mongodbUri ) ;
19- if ( this . mongodbUri ) await updateDotenv ( { MONGODB_URI : this . mongodbUri } ) ;
12+ async connect ( mongodbUri : string ) {
13+ logger . info ( 'Connecting to the database' , mongodbUri ) ;
2014 try {
21- this . mongoose = await mongoose . connect ( this . mongodbUri , {
15+ this . mongoose = await mongoose . connect ( mongodbUri , {
2216 socketTimeoutMS : 90000 ,
2317 connectTimeoutMS : 60000 ,
2418 serverSelectionTimeoutMS : 30000 ,
@@ -41,14 +35,27 @@ class Database {
4135 // logger.debug(`\x1B[0;36mMongoose:\x1B[0m: ${collectionName}.${methodName}` + `(${methodArgs.map(msgMapper).join(', ')})`);
4236 logger . debug ( `[Mongoose] ${ collectionName } .${ methodName } (${ methodArgs . map ( msgMapper ) . join ( ', ' ) } )` ) ;
4337 } ) ;
44-
38+
39+ if ( mongodbUri ) await updateDotenv ( { MONGODB_URI : mongodbUri } ) ;
40+ this . mongodbUri = mongodbUri ;
41+ logger . info ( 'Database connected' ) ;
42+
43+ this . setupSchemas ( ) ;
44+ logger . info ( 'Database schemas setup complete' ) ;
4545 } catch ( error ) {
4646 logger . debug ( error ) ;
4747 if ( error instanceof Error ) {
4848 logger . error ( `Database connection error: ${ error . message } ` ) ;
4949 }
5050 throw error ;
5151 }
52+ }
53+
54+ async disconnect ( ) {
55+ await this . mongoose ?. disconnect ( ) ;
56+ }
57+
58+ async setupSchemas ( ) {
5259 mongoose . model ( 'Settings' , new mongoose . Schema ( {
5360 name : String ,
5461 value : { }
@@ -361,10 +368,6 @@ class Database {
361368 mongoose . model ( 'Counter' , CounterSchema ) ;
362369 }
363370
364- async disconnect ( ) {
365- await this . mongoose ?. disconnect ( ) ;
366- }
367-
368371}
369372
370373export default Database ;
0 commit comments