Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

health check API 에서 db connection 확인 #314

Merged
merged 1 commit into from
Aug 3, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion src/api/routes/RootRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,25 @@ import ExpressPromiseRouter from 'express-promise-router';
import MonitorRouter = require('./MonitorRouter');
import StaticPageRouter = require('./StaticPageRouter');
import ApiRouter = require('./ApiRouter');
import mongoose = require('mongoose');

let router = ExpressPromiseRouter();

router.get('/health-check', (req, res) => res.sendStatus(200));
router.get('/health-check', (req, res) => {
if (mongoose.connection.readyState !== 1) {
Copy link
Member Author

@davin111 davin111 Aug 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

밑에서 ping 하는데 이걸 굳이 왜 했지? 싶을 수 있는데.

애당초 최초 connection 부터 망가져 있는 경우에는, 밑에 mongoose.connection.db 쪽에서 TypeError: Cannot read property 'method' of undefined 에러가 발생하고, 이것이 읽기 좋지 않아 본질을 흐리기에 미리 체크하고 가는 것.

mongoose.connection.readyState의 경우에는 ping 과 달리 별도의 db 자원을 소모하지 않음.

res.status(500).json({ message: 'MongoDB connection failed' });
return;
}

mongoose.connection.db.admin().ping((err, result) => {
if (err) {
res.status(500).json({ message: 'MongoDB connection failed' });
return;
}
res.status(200).json({ message: 'ok' });
});
});

router.use('/monitor', MonitorRouter);

router.use(function(req, res) {
Expand Down
Loading