Skip to content

Commit

Permalink
Write cache tests
Browse files Browse the repository at this point in the history
  • Loading branch information
karelhala committed Sep 14, 2020
1 parent 49d6e18 commit 5508479
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 6 deletions.
7 changes: 6 additions & 1 deletion src/js/entry.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import { fetchPermissions } from './rbac/fetchPermissions';
import { getUrl } from './utils';
import flatMap from 'lodash/flatMap';
import { headerLoader } from './App/Header';
import { decodeToken } from './jwt/jwt';
import { CacheAdapter } from './utils/cache';

const NoAccess = lazy(() => import(/* webpackChunkName: "NoAccess" */ './App/NoAccess'));

Expand Down Expand Up @@ -51,11 +53,14 @@ export function chromeInit(libjwt) {
// public API actions
const { identifyApp, appNav, appNavClick, clearActive, appAction, appObjectId, chromeNavUpdate } = actions;

let chromeCache;

// Init JWT first.
const jwtResolver = libjwt.initPromise
.then(async () => {
const user = await libjwt.jwt.getUserInfo();
actions.userLogIn(user);
chromeCache = new CacheAdapter('chrome', `${decodeToken(libjwt.jwt.getEncodedToken())?.session_state}-chrome`);
headerLoader();
})
.catch(() => {
Expand All @@ -68,7 +73,7 @@ export function chromeInit(libjwt) {
// Load navigation after login
const navResolver = jwtResolver.then(async () => {
const navigationYml = await sourceOfTruth(libjwt.jwt.getEncodedToken());
const navigationData = await loadNav(navigationYml);
const navigationData = await loadNav(navigationYml, chromeCache);
chromeNavUpdate(navigationData);
});

Expand Down
8 changes: 6 additions & 2 deletions src/js/nav/globalNav.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,12 @@ async function getAppData(appId, propName, masterConfig) {
}
}

export async function loadNav(yamlConfig) {
const groupedNav = await getNavFromConfig(safeLoad(yamlConfig));
export async function loadNav(yamlConfig, cache) {
let groupedNav = await cache.getItem('navigation');
if (!groupedNav) {
groupedNav = await getNavFromConfig(safeLoad(yamlConfig));
cache.setItem('navigation', groupedNav);
}

const [active, section] = [getUrl('bundle'), getUrl('app')];
const globalNav = (groupedNav[active] || groupedNav.insights)?.routes;
Expand Down
5 changes: 2 additions & 3 deletions src/js/utils/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export const createCacheStore = (endpoint, cacheKey) => {
driver: [
localforage.LOCALSTORAGE
],
name: name.split('/')[0] || name
name: name?.split('/')[0] || name
});
};

Expand All @@ -18,16 +18,15 @@ let store;
export class CacheAdapter {
constructor(endpoint, cacheKey, maxAge = 10 * 60 * 1000) {
this.maxAge = maxAge;
this.expires = (new Date()).getTime() + this.maxAge;
if (!store) {
const name = lastActive(endpoint, cacheKey);
let cached;
try {
cached = JSON.parse(localStorage.getItem(name));
} catch (e) {
console.log(e);
cached = localStorage.getItem(name);
}
console.log(cached, 'this is cached', name);
this.name = name;
this.endpoint = endpoint;
this.cacheKey = cacheKey;
Expand Down
52 changes: 52 additions & 0 deletions src/js/utils/cache.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
const cache = require('./cache');
const setItem = jest.fn();
const getItem = jest.fn();
Object.defineProperty(window, 'localStorage', { value: {
setItem,
getItem
} });
cache.__set__('localforage', ({
createInstance: () => ({
setItem: async (key, data) => window.localStorage.setItem(key, data),
getItem: async (key) => {
window.localStorage.getItem(key);
return JSON.parse('{"data": {}, "expires": 1}');
}
}),
dropInstance: async () => {}
}));

describe('CacheAdapter', () => {
beforeEach(() => {
cache.__set__('store', undefined);
});

it('should create empty cache', () => {
const store = new cache.CacheAdapter('test/test', 'test');
expect(getItem).toHaveBeenCalled();
expect(store.expires > (new Date()).getTime()).toBe(true);
});

it('should invalidate store', (done) => {
const store = new cache.CacheAdapter('test/test', 'test', 1);
setTimeout(async () => {
expect(store.expires < (new Date()).getTime()).toBe(true);
await store.setItem('something', 'data');
done();
}, 2);
});

it('should get item', async () => {
const store = new cache.CacheAdapter('test/test', 'test');
await store.getItem('something');
});

it('should get store from memory', () => {
Object.defineProperty(window, 'localStorage', { value: {
setItem,
getItem: () => JSON.stringify({
expires: (new Date()).getTime + 10000
})
} });
});
});

0 comments on commit 5508479

Please sign in to comment.