Chore: make populateSettings middleware use node-cache

This commit is contained in:
csrapr 2021-05-07 17:23:47 +01:00 committed by Josh Harvey
parent fb4267b0d5
commit 7657da5e16
5 changed files with 29 additions and 45 deletions

View file

@ -1,9 +1,8 @@
const state = require('./state')
const settingsCache = require('./settingsCache')
const newSettingsLoader = require('../new-settings-loader')
const helpers = require('../route-helpers')
const SETTINGS_CACHE_REFRESH = 60 * 60 * 1000
const { settingsCache } = state
const populateSettings = function (req, res, next) {
const operatorId = res.locals.operatorId
@ -13,21 +12,16 @@ const populateSettings = function (req, res, next) {
}
try {
// Clear cache every hour
if (Date.now() - settingsCache.getTimestamp(operatorId) > SETTINGS_CACHE_REFRESH) {
settingsCache.clear(operatorId)
}
if (!versionId && settingsCache.getCache(operatorId)) {
req.settings = settingsCache.getCache(operatorId)
const operatorSettings = settingsCache.get(operatorId)
if (!versionId && operatorSettings) {
req.settings = operatorSettings
return next()
}
if (!versionId && !settingsCache.getCache(operatorId)) {
if (!versionId && !operatorSettings) {
return newSettingsLoader.loadLatest()
.then(settings => {
settingsCache.setCache(operatorId, settings)
settingsCache.setTimestamp(operatorId, Date.now())
settingsCache.set(operatorId, settings)
req.settings = settings
})
.then(() => next())