Skip to content

Commit

Permalink
build: testing deployment
Browse files Browse the repository at this point in the history
  • Loading branch information
cyberboyanmol committed Aug 28, 2024
1 parent 47658da commit bdda749
Show file tree
Hide file tree
Showing 4 changed files with 90 additions and 34 deletions.
14 changes: 13 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export class App {
private dalService: DalService
constructor(routes: Routes[]) {
this.app = new OpenAPIHono()
this.dalService = new DalService()
this.dalService = DalService.getInstance()
this.initializeApp(routes)
}
private async initializeApp(routes: Routes[]) {
Expand All @@ -38,6 +38,17 @@ export class App {
}

private initializeGlobalMiddleware() {
this.app.use(async (c, next) => {
try {
await this.dalService.connectDB()
await next()
} catch (error) {
console.error('Database connection error:', error)
return c.json({ error: 'Internal Server Error' }, 500)
} finally {
// await this.dalService.cleanup()
}
})
this.app.use(
cors({
origin: '*',
Expand All @@ -53,6 +64,7 @@ export class App {
const end = Date.now()
c.res.headers.set('X-Response-Time', `${end - start}ms`)
})

this.app.use(authMiddleware)
}

Expand Down
105 changes: 76 additions & 29 deletions src/infra/mongodb/dal.service.ts
Original file line number Diff line number Diff line change
@@ -1,55 +1,102 @@
import { Connection } from 'mongoose'
import * as mongoose from 'mongoose'
import mongoose, { Connection } from 'mongoose'

let cachedConnection: Connection | null = null
let connectionPromise: Promise<Connection> | null = null

export class DalService {
private connection: Connection | undefined
private static instance: DalService

private constructor() {}

static getInstance(): DalService {
if (!DalService.instance) {
DalService.instance = new DalService()
}
return DalService.instance
}

constructor() {}
async connectDB(): Promise<Connection> {
if (cachedConnection && this.isConnected()) {
return cachedConnection
}

if (!process.env.EXERCISEDB_DATABASE) {
throw new Error('EXERCISEDB_DATABASE environment variable is not set')
}

async connectDB(): Promise<Connection | undefined> {
if (this.connection && this.isConnected()) {
return this.connection
if (!connectionPromise) {
connectionPromise = mongoose
.connect(process.env.EXERCISEDB_DATABASE, {
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000,
maxPoolSize: 1,
minPoolSize: 0,
maxIdleTimeMS: 10000
})
.then((conn) => {
console.log('Database connected successfully')
return conn.connection
})
.catch((error) => {
console.error('Error connecting to the database:', error)
connectionPromise = null
throw error
})
}

try {
if (process.env.EXERCISEDB_DATABASE !== undefined) {
const instance = await mongoose.connect(process.env.EXERCISEDB_DATABASE)
console.log('Database connected successfully')
this.connection = instance.connection
return this.connection
}
cachedConnection = await connectionPromise
return cachedConnection
} catch (error) {
console.error('Error connecting to the database:', error)
throw new Error('Error connecting to the database')
}
}

isConnected(): boolean {
return this.connection?.readyState === 1
return cachedConnection?.readyState === 1
}

async disconnect() {
try {
await mongoose.disconnect()
console.log('Database disconnected successfully')
} catch (error) {
console.error('Error disconnecting from the database:', error)
throw error
async disconnect(): Promise<void> {
if (cachedConnection) {
try {
await mongoose.disconnect()
cachedConnection = null
connectionPromise = null
console.log('Database disconnected successfully')
} catch (error) {
console.error('Error disconnecting from the database:', error)
throw error
}
}
}

/**
* The `destroy` function drops the database only in a test environment.
*/
async destroy() {
if (process.env.NODE_ENV !== 'test') throw new Error('Allowed only in test environment')
async destroy(): Promise<void> {
if (process.env.NODE_ENV !== 'test') {
throw new Error('Allowed only in test environment')
}

try {
await mongoose.connection.dropDatabase()
console.log('Database dropped successfully')
if (cachedConnection) {
await cachedConnection.dropDatabase()
console.log('Database dropped successfully')
}
} catch (error) {
console.error('Error dropping the database:', error)
throw error
} finally {
await this.disconnect()
}
}
async closeConnection(): Promise<void> {
if (cachedConnection) {
await cachedConnection.close()
cachedConnection = null
connectionPromise = null
console.log('Database connection closed')
}
}

async cleanup(): Promise<void> {
await this.closeConnection()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export class GetExercisesUseCase implements IUseCase<GetExercisesArgs, GetExerci
const totalPages = Math.ceil(totalCount / safeLimit)
const currentPage = Math.floor(safeOffset / safeLimit) + 1

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

return {
totalPages,
Expand Down
3 changes: 0 additions & 3 deletions src/server.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { BodyPartController, EquipmentController, MuscleController, ExerciseController } from './modules'
import { DalService } from '#infra/mongodb/dal.service.js'
import { App } from './app'
import { ImagesController } from '#modules/images/controllers/image.controller.js'
import { UserController } from '#modules/users/controllers/user.controller.js'

const dalService = new DalService()
const app = new App([
new ExerciseController(),
new MuscleController(),
Expand All @@ -13,6 +11,5 @@ const app = new App([
new ImagesController(),
new UserController()
]).getApp()
await dalService.connectDB()

export default app

0 comments on commit bdda749

Please sign in to comment.