Skip to content

Commit

Permalink
feature: Automatically clear cache when -T changed
Browse files Browse the repository at this point in the history
  • Loading branch information
dzz007 committed Mar 30, 2021
1 parent ecce45d commit 3328401
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 7 deletions.
6 changes: 6 additions & 0 deletions lib/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
11 changes: 6 additions & 5 deletions lib/helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
19 changes: 17 additions & 2 deletions lib/plugins/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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) {
Expand Down

0 comments on commit 3328401

Please sign in to comment.