Skip to content

Commit

Permalink
chore: add logic to close dB connections after it's been used
Browse files Browse the repository at this point in the history
  • Loading branch information
timeowilliams committed Aug 25, 2024
1 parent 2e83987 commit c6f7a39
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
10 changes: 9 additions & 1 deletion backend/src/connectToDB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,13 @@ async function connectToDB(): Promise<typeof mongoose> {
throw error
}
}
async function closeDBConnection(): Promise<void> {
try {
await mongoose.connection.close()
console.log('Disconnected successfully from MongoDB server')
} catch (error) {
console.error('Error closing the database connection:', error)
}
}

export { connectToDB }
export { connectToDB, closeDBConnection }
9 changes: 8 additions & 1 deletion backend/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import jwt from 'jsonwebtoken'
import cors from 'cors'
import bcrypt from 'bcrypt'
import dotenv from 'dotenv'
import { connectToDB } from './connectToDB'
import { connectToDB, closeDBConnection } from './connectToDB'
import User from './models/User'

export const app = express()
Expand Down Expand Up @@ -66,6 +66,8 @@ app.post('/api/v1/auth/signup', async (req, res) => {
} catch (error) {
console.error('Signup error:', error)
res.status(500).send('Server error')
} finally {
await closeDBConnection()
}
})

Expand Down Expand Up @@ -95,6 +97,8 @@ app.post('/api/v1/auth/login', async (req, res) => {
} catch (error) {
console.error('Login error:', error)
res.status(500).send('Server error')
} finally {
await closeDBConnection()
}
})

Expand All @@ -103,13 +107,16 @@ app.delete('/api/v1/auth/delete', async (req, res) => {
const { username } = req.body

try {
await connectToDB()
const user = await User.findOneAndDelete({ username })
if (!user) {
return res.status(404).send('User not found')
}
res.status(200).send('User deleted successfully')
} catch (error) {
res.status(500).send('Internal server error')
} finally {
await closeDBConnection()
}
})

Expand Down

0 comments on commit c6f7a39

Please sign in to comment.