From 3328401ede8158873dab96baa2ffa32e11336fe5 Mon Sep 17 00:00:00 2001 From: Zhizhang Deng Date: Tue, 30 Mar 2021 15:41:12 -0400 Subject: [PATCH] feature: Automatically clear cache when -T changed --- lib/cache.js | 6 ++++++ lib/helper.js | 11 ++++++----- lib/plugins/cache.js | 19 +++++++++++++++++-- 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/lib/cache.js b/lib/cache.js index 42efad0b..dc10d52e 100644 --- a/lib/cache.js +++ b/lib/cache.js @@ -9,6 +9,12 @@ cache.init = function() { file.mkdir(file.cacheDir()); }; +cache.deleteAll = function () { + cache.list().forEach(value => { + cache.del(value.name); + }) +}; + cache.get = function(k) { const fullpath = file.cacheFile(k); if (!file.exist(fullpath)) return null; diff --git a/lib/helper.js b/lib/helper.js index d256103e..9c5ff43f 100644 --- a/lib/helper.js +++ b/lib/helper.js @@ -52,11 +52,12 @@ const LANGS = [ const h = {}; h.KEYS = { - user: '../user', - stat: '../stat', - plugins: '../../plugins', - problems: 'problems', - problem: p => p.fid + '.' + p.slug + '.' + p.category + user: '../user', + stat: '../stat', + plugins: '../../plugins', + problems: 'problems', + translation: 'translationConfig', + problem: p => p.fid + '.' + p.slug + '.' + p.category }; h.prettyState = function(state) { diff --git a/lib/plugins/cache.js b/lib/plugins/cache.js index e3a132c2..d6316861 100644 --- a/lib/plugins/cache.js +++ b/lib/plugins/cache.js @@ -9,7 +9,21 @@ var session = require('../session'); const plugin = new Plugin(50, 'cache', '', 'Plugin to provide local cache.'); -plugin.getProblems = function(needTranslation, cb) { +// this function will clear all caches if needTranslation is different than stored +// it will also store the new needTranslation into cache automatically +function clearCacheIfTchanged(needTranslation) { + const translationConfig = cache.get(h.KEYS.translation); + if (!translationConfig || translationConfig['useEndpointTranslation'] != needTranslation) { + // cache doesn't have the key => old cache version, need to update + // or cache does have the key but it contains a different value + cache.deleteAll(); + cache.set(h.KEYS.translation, { useEndpointTranslation: needTranslation }); + log.debug('cache cleared: -T option changed'); + } +} + +plugin.getProblems = function (needTranslation, cb) { + clearCacheIfTchanged(needTranslation); const problems = cache.get(h.KEYS.problems); if (problems) { log.debug('cache hit: problems.json'); @@ -24,7 +38,8 @@ plugin.getProblems = function(needTranslation, cb) { }); }; -plugin.getProblem = function(problem, needTranslation, cb) { +plugin.getProblem = function (problem, needTranslation, cb) { + clearCacheIfTchanged(needTranslation); const k = h.KEYS.problem(problem); const _problem = cache.get(k); if (_problem) {