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())

View file

@ -1,32 +0,0 @@
const _ = require('lodash/fp')
const state = require('./state')
const getTimestamp = (operatorId) => {
if (!operatorId) throw new Error('operatorId must not be nil or empty')
return state.settingsCache[operatorId] ? state.settingsCache[operatorId].timestamp : null
}
const getCache = (operatorId) => {
if (!operatorId) throw new Error('operatorId must not be nil or empty')
return state.settingsCache[operatorId] ? state.settingsCache[operatorId].cache : null
}
const setTimestamp = (operatorId, newTimestamp) => {
state.settingsCache = _.set([operatorId, 'timestamp'], newTimestamp, state.settingsCache)
}
const setCache = (operatorId, newCache) => {
state.settingsCache = _.set([operatorId, 'cache'], newCache, state.settingsCache)
}
const clear = (operatorId) => {
state.settingsCache = _.set([operatorId], null, state.settingsCache)
}
module.exports = {
getTimestamp,
getCache,
setTimestamp,
setCache,
clear
}

View file

@ -1,7 +1,13 @@
const NodeCache = require('node-cache')
const SETTINGS_CACHE_REFRESH = 3600
module.exports = (function () {
return {
oldVersionId: 'unset',
settingsCache: {},
settingsCache: new NodeCache({
stdTTL: SETTINGS_CACHE_REFRESH,
checkperiod: SETTINGS_CACHE_REFRESH // Clear cache every hour
}),
canLogClockSkewMap: {},
canGetLastSeenMap: {},
pids: {},