Log version check info when app is starting

Signed-off-by: Yukai Huang <yukaihuangtw@gmail.com>
This commit is contained in:
Yukai Huang 2020-02-06 10:40:51 +08:00
parent 334c81efe7
commit 8cd9ba2f82
2 changed files with 32 additions and 8 deletions

3
app.js
View File

@ -25,7 +25,7 @@ var response = require('./lib/response')
var models = require('./lib/models') var models = require('./lib/models')
var csp = require('./lib/csp') var csp = require('./lib/csp')
const { versionCheckMiddleware } = require('./lib/web/middleware/checkVersion') const { versionCheckMiddleware, checkVersion } = require('./lib/web/middleware/checkVersion')
function createHttpServer () { function createHttpServer () {
if (config.useSSL) { if (config.useSSL) {
@ -170,6 +170,7 @@ app.use(require('./lib/middleware/redirectWithoutTrailingSlashes'))
app.use(require('./lib/middleware/codiMDVersion')) app.use(require('./lib/middleware/codiMDVersion'))
if (config.autoVersionCheck) { if (config.autoVersionCheck) {
checkVersion(app)
app.use(versionCheckMiddleware) app.use(versionCheckMiddleware)
} }

View File

@ -14,9 +14,13 @@ const CHECK_TIMEOUT = 1000 * 60 * 60 * 24 // 1 day
const rp = promisify(request) const rp = promisify(request)
exports.versionCheckMiddleware = async function (req, res, next) { exports.checkVersion = checkVersion
/**
* @param {Express.Application|Express.Request} ctx
*/
async function checkVersion (ctx) {
if (lastCheckAt && (lastCheckAt + CHECK_TIMEOUT > Date.now())) { if (lastCheckAt && (lastCheckAt + CHECK_TIMEOUT > Date.now())) {
return next() return
} }
// update lastCheckAt whether the check would fail or not // update lastCheckAt whether the check would fail or not
@ -31,17 +35,36 @@ exports.versionCheckMiddleware = async function (req, res, next) {
if (statusCode !== 200 || data.status === 'error') { if (statusCode !== 200 || data.status === 'error') {
logger.error('Version check failed.') logger.error('Version check failed.')
return next() return
} }
req.app.locals.versionInfo.latest = data.latest let locals = ctx.locals ? ctx.locals : ctx.app.locals
req.app.locals.versionInfo.versionItem = req.app.locals.latest ? null : data.versionItem
return next() locals.versionInfo.latest = data.latest
locals.versionInfo.versionItem = data.latest ? null : data.versionItem
if (!data.latest) {
const { version, link } = data.versionItem
logger.warn(`Your CodiMD version is out of date! The latest version is ${version}. Please see what's new on ${link}.`)
}
return
} catch (err) { } catch (err) {
// ignore and skip version check // ignore and skip version check
logger.error('Version check failed.') logger.error('Version check failed.')
logger.error(err) logger.error(err)
return next()
return
} }
} }
exports.versionCheckMiddleware = function (req, res, next) {
checkVersion(req)
.then(() => {
next()
})
.catch((err) => {
next()
})
}