Skip to content

Commit bdda749

Browse files
committed
build: testing deployment
1 parent 47658da commit bdda749

File tree

4 files changed

+90
-34
lines changed

4 files changed

+90
-34
lines changed

src/app.ts

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ export class App {
1313
private dalService: DalService
1414
constructor(routes: Routes[]) {
1515
this.app = new OpenAPIHono()
16-
this.dalService = new DalService()
16+
this.dalService = DalService.getInstance()
1717
this.initializeApp(routes)
1818
}
1919
private async initializeApp(routes: Routes[]) {
@@ -38,6 +38,17 @@ export class App {
3838
}
3939

4040
private initializeGlobalMiddleware() {
41+
this.app.use(async (c, next) => {
42+
try {
43+
await this.dalService.connectDB()
44+
await next()
45+
} catch (error) {
46+
console.error('Database connection error:', error)
47+
return c.json({ error: 'Internal Server Error' }, 500)
48+
} finally {
49+
// await this.dalService.cleanup()
50+
}
51+
})
4152
this.app.use(
4253
cors({
4354
origin: '*',
@@ -53,6 +64,7 @@ export class App {
5364
const end = Date.now()
5465
c.res.headers.set('X-Response-Time', `${end - start}ms`)
5566
})
67+
5668
this.app.use(authMiddleware)
5769
}
5870

src/infra/mongodb/dal.service.ts

Lines changed: 76 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,102 @@
1-
import { Connection } from 'mongoose'
2-
import * as mongoose from 'mongoose'
1+
import mongoose, { Connection } from 'mongoose'
2+
3+
let cachedConnection: Connection | null = null
4+
let connectionPromise: Promise<Connection> | null = null
35

46
export class DalService {
5-
private connection: Connection | undefined
7+
private static instance: DalService
8+
9+
private constructor() {}
10+
11+
static getInstance(): DalService {
12+
if (!DalService.instance) {
13+
DalService.instance = new DalService()
14+
}
15+
return DalService.instance
16+
}
617

7-
constructor() {}
18+
async connectDB(): Promise<Connection> {
19+
if (cachedConnection && this.isConnected()) {
20+
return cachedConnection
21+
}
22+
23+
if (!process.env.EXERCISEDB_DATABASE) {
24+
throw new Error('EXERCISEDB_DATABASE environment variable is not set')
25+
}
826

9-
async connectDB(): Promise<Connection | undefined> {
10-
if (this.connection && this.isConnected()) {
11-
return this.connection
27+
if (!connectionPromise) {
28+
connectionPromise = mongoose
29+
.connect(process.env.EXERCISEDB_DATABASE, {
30+
serverSelectionTimeoutMS: 5000,
31+
socketTimeoutMS: 45000,
32+
maxPoolSize: 1,
33+
minPoolSize: 0,
34+
maxIdleTimeMS: 10000
35+
})
36+
.then((conn) => {
37+
console.log('Database connected successfully')
38+
return conn.connection
39+
})
40+
.catch((error) => {
41+
console.error('Error connecting to the database:', error)
42+
connectionPromise = null
43+
throw error
44+
})
1245
}
1346

1447
try {
15-
if (process.env.EXERCISEDB_DATABASE !== undefined) {
16-
const instance = await mongoose.connect(process.env.EXERCISEDB_DATABASE)
17-
console.log('Database connected successfully')
18-
this.connection = instance.connection
19-
return this.connection
20-
}
48+
cachedConnection = await connectionPromise
49+
return cachedConnection
2150
} catch (error) {
22-
console.error('Error connecting to the database:', error)
2351
throw new Error('Error connecting to the database')
2452
}
2553
}
2654

2755
isConnected(): boolean {
28-
return this.connection?.readyState === 1
56+
return cachedConnection?.readyState === 1
2957
}
3058

31-
async disconnect() {
32-
try {
33-
await mongoose.disconnect()
34-
console.log('Database disconnected successfully')
35-
} catch (error) {
36-
console.error('Error disconnecting from the database:', error)
37-
throw error
59+
async disconnect(): Promise<void> {
60+
if (cachedConnection) {
61+
try {
62+
await mongoose.disconnect()
63+
cachedConnection = null
64+
connectionPromise = null
65+
console.log('Database disconnected successfully')
66+
} catch (error) {
67+
console.error('Error disconnecting from the database:', error)
68+
throw error
69+
}
3870
}
3971
}
4072

41-
/**
42-
* The `destroy` function drops the database only in a test environment.
43-
*/
44-
async destroy() {
45-
if (process.env.NODE_ENV !== 'test') throw new Error('Allowed only in test environment')
73+
async destroy(): Promise<void> {
74+
if (process.env.NODE_ENV !== 'test') {
75+
throw new Error('Allowed only in test environment')
76+
}
4677

4778
try {
48-
await mongoose.connection.dropDatabase()
49-
console.log('Database dropped successfully')
79+
if (cachedConnection) {
80+
await cachedConnection.dropDatabase()
81+
console.log('Database dropped successfully')
82+
}
5083
} catch (error) {
5184
console.error('Error dropping the database:', error)
5285
throw error
86+
} finally {
87+
await this.disconnect()
5388
}
5489
}
90+
async closeConnection(): Promise<void> {
91+
if (cachedConnection) {
92+
await cachedConnection.close()
93+
cachedConnection = null
94+
connectionPromise = null
95+
console.log('Database connection closed')
96+
}
97+
}
98+
99+
async cleanup(): Promise<void> {
100+
await this.closeConnection()
101+
}
55102
}

src/modules/exercises/use-cases/get-exercises/get-exercise.usecase.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ export class GetExercisesUseCase implements IUseCase<GetExercisesArgs, GetExerci
2727
const totalPages = Math.ceil(totalCount / safeLimit)
2828
const currentPage = Math.floor(safeOffset / safeLimit) + 1
2929

30-
const result = await this.exerciseModel.find(query).sort(sort).skip(safeOffset).limit(safeLimit).exec()
30+
const result = await this.exerciseModel.find(query).sort(sort).skip(safeOffset).limit(safeLimit).lean().exec()
3131

3232
return {
3333
totalPages,

src/server.ts

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
import { BodyPartController, EquipmentController, MuscleController, ExerciseController } from './modules'
2-
import { DalService } from '#infra/mongodb/dal.service.js'
32
import { App } from './app'
43
import { ImagesController } from '#modules/images/controllers/image.controller.js'
54
import { UserController } from '#modules/users/controllers/user.controller.js'
65

7-
const dalService = new DalService()
86
const app = new App([
97
new ExerciseController(),
108
new MuscleController(),
@@ -13,6 +11,5 @@ const app = new App([
1311
new ImagesController(),
1412
new UserController()
1513
]).getApp()
16-
await dalService.connectDB()
1714

1815
export default app

0 commit comments

Comments
 (0)