Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(locale): introducing cache busting logic #4325

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 38 additions & 4 deletions packages/services/src/services/Locale/Locale.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,14 @@ const _axiosConfig = {
*/
const _sessionListKey = 'dds-countrylist';

/**
* Two hours in milliseconds to compare session timestamp.
*
* @type {number}
* @private
*/
const _twoHours = 60 * 60 * 2000;

/**
* Use the <html> lang attr to determine a return locale object
*
Expand Down Expand Up @@ -300,10 +308,9 @@ class LocaleAPI {
* @param {Function} reject rejects the promise
*/
static fetchList(cc, lc, resolve, reject) {
const sessionList =
typeof sessionStorage === 'undefined'
? undefined
: JSON.parse(sessionStorage.getItem(`${_sessionListKey}-${cc}-${lc}`));
const itemKey = `${_sessionListKey}-${cc}-${lc}`;

const sessionList = this.getSessionCache(itemKey);

if (sessionList) {
resolve(sessionList);
Expand All @@ -313,6 +320,7 @@ class LocaleAPI {
const url = `${_endpoint}/${cc}${lc}-utf8.json`;
_requestsList[key] = axios.get(url, _axiosConfig).then(response => {
const { data } = response;
data['timestamp'] = Date.now();
sessionStorage.setItem(
`${_sessionListKey}-${cc}-${lc}`,
JSON.stringify(data)
Expand Down Expand Up @@ -373,6 +381,32 @@ class LocaleAPI {
}
return locale;
}

/**
* Retrieves session cache and checks if cache needs to be refreshed
*
* @param {string} key session storage key
* @returns {object} session storage object
*/
static getSessionCache(key) {
const session =
typeof sessionStorage === 'undefined'
? undefined
: JSON.parse(sessionStorage.getItem(key));

if (!session || !session.timestamp) {
return;
}

const currentTime = Date.now(),
timeDiff = currentTime - session.timestamp;

if (timeDiff > _twoHours) {
sessionStorage.removeItem(key);
return;
}
return session;
}
}

export default LocaleAPI;
48 changes: 48 additions & 0 deletions packages/services/src/services/Locale/__tests__/Locale.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { geolocation, ipcinfoCookie } from '@carbon/ibmdotcom-utilities';
import digitalDataResponse from '../../DDO/__tests__/data/response.json';
import LocaleAPI from '../Locale';
import mockAxios from 'axios';
import oldSession from './data/timestamp_response.json';
import response from './data/response.json';
import root from 'window-or-global';

Expand Down Expand Up @@ -488,6 +489,53 @@ describe('LocaleAPI', () => {
expect(mockAxios.get).toHaveBeenCalledTimes(2);
});

it('should update the cached response if session is old', async () => {
// mock storage for specific test
const sessionStorageMock = (() => {
let cache = {};

return {
getItem(key) {
return cache[key] || null;
},
setItem(key, value) {
cache[key] = value;
},
removeItem(key) {
delete cache[key];
},
clear() {
cache = {};
},
};
})();

Object.defineProperty(window, 'sessionStorage', {
value: sessionStorageMock,
});

const mockDate = 1546300800000; // Epoch time of January 1, 2019 midnight UTC
global.Date.now = jest.fn(() => mockDate);

// using very old cached session
sessionStorageMock.setItem(
'dds-countrylist-us-en',
JSON.stringify(Object.assign(oldSession, { CACHE: true }))
);

await LocaleAPI.getList({
cc: 'us',
lc: 'en',
});

const newSession = JSON.parse(
sessionStorageMock.getItem('dds-countrylist-us-en')
);

// fresh cached data would lack this property
expect(newSession).not.toHaveProperty('CACHE');
});

afterEach(() => {
for (let handle = handles.pop(); handle; handle = handles.pop()) {
handle.release();
Expand Down
Loading