Skip to content

Commit

Permalink
[#7] refactor: move mongoose connection logic into seperate util file
Browse files Browse the repository at this point in the history
  • Loading branch information
glemenneo committed Sep 18, 2024
1 parent bebf79e commit 3bfa665
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 15 deletions.
12 changes: 12 additions & 0 deletions backend/user-service/src/common/mongodb.util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { connect } from 'mongoose'
import logger from './logger.util'

export default async (connectionString: string): Promise<void> => {
await connect(connectionString)
.then(() => {
logger.info(`[Init] Connected to database`)
})
.catch((error: Error) => {
logger.error(`[Init] Failed to connect to database: ${error.message}`)
})
}
24 changes: 9 additions & 15 deletions backend/user-service/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,19 @@
import 'dotenv/config'
import http, { Server } from 'http'
import { connect } from 'mongoose'
import logger from './common/logger.util'
import connectToDatabase from './common/mongodb.util'
import index from './index'

const port: string = process.env.PORT ?? '3000'
const dbUrl: string | undefined = process.env.DB_URL
if (!dbUrl) {
logger.error(`[Init] DB_URL is not set`)
}

const server: Server = http.createServer(index)

connect(dbUrl!)
.then(() => {
logger.info(`[Init] Connected to MongoDB`)
})
.catch((error: Error) => {
logger.error(`[Init] ${error.message}`)
})

server.listen(port, async () => {
logger.info(`[Init] Server is listening on port ${port}`)
})

const connectionString: string | undefined = process.env.DB_URL
if (!connectionString) {
logger.error(`[Init] DB_URL is not set`)
process.exit(1)
}

connectToDatabase(connectionString)

0 comments on commit 3bfa665

Please sign in to comment.