Skip to content

Commit

Permalink
feat: improve service worker logic
Browse files Browse the repository at this point in the history
This change includes the following:

* Adds support for caching API requests
* Improves the way the app is updated
* Fixes potential issues with the registration of the service worker (for some reason, AOT strips away the `environment.swLocation` variable so we have no choice but to hardcode it)
  • Loading branch information
EdricChan03 committed Jan 4, 2020
1 parent 9f4bf65 commit 12c25d0
Show file tree
Hide file tree
Showing 5 changed files with 89 additions and 9 deletions.
29 changes: 29 additions & 0 deletions projects/rss-reader/ngsw-config.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,35 @@
{
"$schema": "../../node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"appData": {
"version": "1.5.4"
},
"dataGroups": [
{
"name": "time-based-apis",
"urls": [
"https://newsapi.org/v2/**",
"https://api.rss2json.com/**"
],
"cacheConfig": {
"maxAge": "1h",
"timeout": "5s",
"strategy": "freshness",
"maxSize": 20
}
},
{
"name": "non-time-based-apis",
"urls": [
"https://restcountries.eu/rest/**"
],
"cacheConfig": {
"maxAge": "7d",
"maxSize": 8,
"timeout": "2s"
}
}
],
"assetGroups": [
{
"name": "app",
Expand Down
61 changes: 56 additions & 5 deletions projects/rss-reader/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,20 +172,71 @@ export class AppComponent implements OnInit, OnDestroy {
if (this.isOffline) {
console.log('User is offline');
// tslint:disable-next-line:max-line-length
const snackBarRef = this.shared.openSnackBar({ msg: 'You are currently offline. Some features may not be available.', action: 'Retry', additionalOpts: { panelClass: ['mat-elevation-z2'], horizontalPosition: 'start' } });
const snackBarRef = this.shared.openSnackBar({
msg: 'You are currently offline. Some features may not be available.',
action: 'Retry',
additionalOpts: {
panelClass: ['mat-elevation-z2'],
horizontalPosition: 'start'
}
});
snackBarRef.onAction().subscribe(() => {
window.location.reload();
});
}

// SwUpdate functionality
console.log('SwUpdate#isEnabled:', this.swUpdate.isEnabled);

this.swUpdate.checkForUpdate().then(() => {
console.log('[AppComponent] Successfully checked for updates.');
}, error => {
console.error('[AppComponent] Could not check for updates:', error);
});

this.swUpdate.activated.subscribe(event => {
console.log('[AppComponent] Successfully activated update!');
this.shared.openSnackBar({
msg: 'Successfully updated the app!'
});
console.log('[AppComponent] Current version is:', event.current);
console.log('[AppComponent] Previous version is:', event.previous);
});

this.swUpdate.available.subscribe(event => {
console.log('[App] Update available: current version is', event.current, 'available version is', event.available);
console.log('[AppComponent] Update available: current version is', event.current, 'available version is', event.available);

function hasNewerVer(): boolean {
const availableHasVer = 'version' in event.available.appData;
const currentHasVer = 'version' in event.current.appData;
let returnVal = false;

if ('version' in event.available.appData && currentHasVer) {
// tslint:disable-next-line: no-string-literal
returnVal = event.available.appData['version'] !== event.current.appData['version'];
}

return returnVal;
}

const message = hasNewerVer() ?
`A newer version (${event.available.appData['version']}) of the app is available!` :
'A newer version of the app is available!';
const snackBarRef = this.shared.openSnackBar({
msg: 'A newer version of this app is available!',
action: 'Update & Refresh'
msg: message,
action: 'Update & Refresh',
additionalOpts: {
// Interesting note: The snackbar code actually checks if the duration is above 0 and only enables auto-hide from that.
duration: 0
}
});

snackBarRef.onAction().subscribe(() => {
this.shared.activateUpdate();
this.swUpdate.activateUpdate().then(() => {
window.location.reload();
}, error => {
console.error('[AppComponent] Could not activate update:', error);
});
});

});
Expand Down
3 changes: 2 additions & 1 deletion projects/rss-reader/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ const PIPES = [
AppRoutingModule,
// The scope parameter is specified such that the service worker only
// applies to the /rss-reader URL.
ServiceWorkerModule.register(environment.swLocation, { enabled: environment.production, scope: './' }),
// ServiceWorkerModule.register(environment.swLocation, { enabled: environment.production, scope: './' }),
ServiceWorkerModule.register('./ngsw-worker.js', { enabled: environment.production, scope: './' }),
DialogsModule,
// AngularFireModule.initializeApp(environment.firebase),
// AngularFirestoreModule.enablePersistence(),
Expand Down
2 changes: 1 addition & 1 deletion projects/rss-reader/src/environment.base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export const gitRepoDefaults: GitRepo = {
/** Default environment that other enviroments can extend from. */
export const defaultEnvironment: Environment = {
production: false,
swLocation: '',
swLocation: '/ngsw-worker.js',
latestVersion,
gitRepoDefaults
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { mergeWithDefaultEnv } from '../environment.base';

export const environment = mergeWithDefaultEnv({
production: true,
swLocation: '/ngsw-worker.js'
production: true
});

0 comments on commit 12c25d0

Please sign in to comment.