Mic*_*ryl 9 mongoose mongodb node.js
我们的许多运行 Express/Node.js 的系统都实现了一个/healthcheck端点,我们的负载平衡器和其他监控系统可以监视它以检测我们的一个应用程序何时出现问题。基本上,端点检查与应用程序具有的所有下游依赖项的连接,包括 MongoDB。
这个问题是,当/healthcheck端点尝试运行它的测试事务并且它失败时,没有明显的方法来捕获端点中的错误,以便我可以让它报告 MongoDB 依赖项有问题。相反,服务器会为/healthcheck请求抛出 500 错误(虽然仍然可以检测为问题,但没有那么有用)。
这段代码基本上展示了我们在做什么。它并不完整和可运行,但具有 Mongoose 经验的 Express 用户应该很容易识别它。
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const HealthcheckSchema = new Schema({
widget: {
type: String,
required: true,
unique: false,
},
createdAt: Date,
})
const HealthCheck = mongoose.model('Healthcheck', HealthcheckSchema, 'healthcheck')
const mongoCheck = () => Healthcheck.remove({}).exec()
.then(() => Healthcheck.create({widget: 'xyzpdq'}))
.then((results) => Healthcheck.findOne({widget: results.widget}).exec())
.then(() => true)
.catch(() => false)
const healthCheckEndpoint = (req, res) => {
let status = {}
Promise.all([mongoCheck()]) // normally there are other checks as well
.then(function (values) {
status.mongoUp = values[0]
return res.status(200).json(status) // always return 200; the payload gives the health status, not the HTTP status code
})
}
app.get('/healthcheck', healthCheckEndpoint)
Run Code Online (Sandbox Code Playgroud)
在应用程序的主要设置中,不特定于健康检查,我们使用mongoose.connect()回调。我们有像各种状态的事件处理程序disconnected和error与这样,和这些事件捕捉,但不利于获得在适当的状态/healthcheck端点。
我想我可以使用这些事件处理程序来设置 /healthcheck 可以接收并返回的状态,但我真的更喜欢进行实际查询并使用其成功/失败作为结果。
事实证明这一切都是转移注意力的事情。/healthcheck这里的问题是,在到达端点之前,有一个 Express 中间件层正在使用 Mongo 。
在本例中,它是一个 Mongo 会话管理器。
/healthcheck解决方案是从会话中间件中排除该URL。
function excludeSessionsForStaticURLs (req, res, next) {
if (!new RegExp(/\/about|\/api\/heartbeat|\/healthcheck|\.css|\.js|\.jpg|\.png'/)
.test(req.originalUrl)) {
return sessionMiddleware(req, res, next)
}
return next()
}
app.use(excludeSessionsForStaticURLs)
Run Code Online (Sandbox Code Playgroud)
因此,既然此排除已经到位,Promises 的正常 try/catch (async/await) 和 .catch() 就可以工作,并且 Mongo 的状态在适当的时候反映为 False。
| 归档时间: |
|
| 查看次数: |
205 次 |
| 最近记录: |