Skip to content

Instantly share code, notes, and snippets.

@mb8z
Last active October 3, 2018 18:11
Show Gist options
  • Save mb8z/c19bcb4af1634515d4d2f753bf3087f4 to your computer and use it in GitHub Desktop.
Save mb8z/c19bcb4af1634515d4d2f753bf3087f4 to your computer and use it in GitHub Desktop.
// Cache should work in a way that it takes into consideration:
// 1. Page number and page size
// 2. Applied filters
// Other assumptions:
// 1. It should be stored for up to 5 minutes - for quick access (TODO: TBD)
// 2. It should use localStorage
import _ from 'lodash';
import moment from 'moment';
import LS from '../../../utils/localStorage'; // Available here https://gist.github.com/Ancinek/86d2c136a04c010811d295fb2fb2deab
const Cache = {
cacheLSKey: 'tables-cache',
defaultFilterHash: 'root',
defaultReturnFromCache: { page: 0, pageSize: 0, data: [] },
getFromCache(props = {}) {
const {
appliedFiltersHash = this.defaultFilterHash,
} = props;
const cache = LS.getItem(this.cacheLSKey, {});
if (_.keys(cache).length === 0) {
return this.defaultReturnFromCache;
}
const result = _.get(cache, `${appliedFiltersHash}`);
if (!result) return this.defaultReturnFromCache;
const { pageSize, data } = result;
return {
pageSize,
page: parseFloat(_(data).keys().max()),
data: _.keys(data).reduce((arr, page) => {
const pageData = data[page] || [];
return [...arr, ...pageData];
}, []),
};
},
storeInCache(props) {
const {
appliedFiltersHash = this.defaultFilterHash,
page,
pageSize,
data = [],
} = props;
const cache = LS.getItem(this.cacheLSKey, {});
if (!cache[appliedFiltersHash]) cache[appliedFiltersHash] = {};
const currentTimestamp = moment().unix();
const currentData = _.get(cache, `${appliedFiltersHash}.data`, {});
const currentPageSize = _.get(cache, `${appliedFiltersHash}.pageSize`, {});
const result = {
lastSaveTimestamp: currentTimestamp,
pageSize,
};
if (currentPageSize === pageSize) {
result.data = {
...currentData,
[page]: data,
};
} else {
result.data = { [page]: data };
}
cache[appliedFiltersHash] = result;
LS.setItem(this.cacheLSKey, cache);
return LS.getItem(this.cacheLSKey);
},
clearCache() {
LS.setItem(this.cacheLSKey, {});
},
};
export default Cache;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment