Skip to content

Instantly share code, notes, and snippets.

@LetItRock
Last active January 23, 2020 20:34
Show Gist options
  • Save LetItRock/645369b441abda8b749c7e9f20f99f0f to your computer and use it in GitHub Desktop.
Save LetItRock/645369b441abda8b749c7e9f20f99f0f to your computer and use it in GitHub Desktop.
Webpack Offline plugin - runtime events - show new updates notification once
import { showSuccessBanner } from '@rs/ui-toolkit';
import moment from 'moment';
import * as OfflinePluginRuntime from 'offline-plugin/runtime';
const SW_UPDATE_READY = 'SW_UPDATE_READY';
const WEBPACK_OFFLINE_CACHE_PREFIX = 'webpack-offline:';
const LAST_UPDATED_DATE = 'LAST_UPDATED_DATE';
// dates from cache names sorted
const getDatesFromCacheNames = (keys: string[]) =>
keys
.filter(key => key.startsWith(WEBPACK_OFFLINE_CACHE_PREFIX))
.map(key => moment(new Date(key.replace(WEBPACK_OFFLINE_CACHE_PREFIX, ''))))
.sort((dateOne, dateTwo) => dateOne.valueOf() - dateTwo.valueOf());
OfflinePluginRuntime.install();
OfflinePluginRuntime.install({
onUpdateReady: () => {
caches.keys().then(keys => {
const lastUpdateDateString = localStorage.getItem(LAST_UPDATED_DATE);
const lastUpdateDate = moment(lastUpdateDateString || new Date());
const datesFromCacheNames = getDatesFromCacheNames(keys);
const currentUpdateDate = datesFromCacheNames[datesFromCacheNames.length - 1];
// if current update date is not last updated date
// or there is no last updated date in local storage
if ((!!currentUpdateDate && !currentUpdateDate.isSame(lastUpdateDate)) || !lastUpdateDateString) {
// new updates are ready
showSuccessBanner(SW_UPDATE_READY, {
content: 'The new version of the application is ready',
actionLabel: 'Apply',
onActionClick: () => OfflinePluginRuntime.applyUpdate(),
});
localStorage.setItem(LAST_UPDATED_DATE, currentUpdateDate.format());
}
});
},
onUpdated: () => {
// @ts-ignore
window.location.reload();
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment