Skip to content

Commit

Permalink
refactor(service-worker): move common code into method
Browse files Browse the repository at this point in the history
  • Loading branch information
gkalpak committed Apr 12, 2018
1 parent 080e687 commit c383b1a
Showing 1 changed file with 11 additions and 18 deletions.
29 changes: 11 additions & 18 deletions packages/service-worker/config/src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,6 @@ export class Generator {
hashTable[joinUrls(this.baseHref, file)] = hash;
}, Promise.resolve());


// Figure out the patterns.
const patterns = (group.resources.urls || [])
.map(
glob => glob.startsWith('/') || glob.indexOf('://') !== -1 ?
glob :
joinUrls(this.baseHref, glob))
.map(glob => globToRegex(glob));

return {
name: group.name,
installMode: group.installMode || 'prefetch',
Expand All @@ -69,22 +60,16 @@ export class Generator {
.concat(plainFiles)
.concat(versionedFiles)
.map(url => joinUrls(this.baseHref, url)),
patterns,
patterns: (group.resources.urls || []).map(url => urlToRegex(url, this.baseHref)),
};
}));
}

private processDataGroups(config: Config): Object[] {
return (config.dataGroups || []).map(group => {
const patterns = group.urls
.map(
glob => glob.startsWith('/') || glob.indexOf('://') !== -1 ?
glob :
joinUrls(this.baseHref, glob))
.map(glob => globToRegex(glob));
return {
name: group.name,
patterns,
patterns: group.urls.map(url => urlToRegex(url, this.baseHref)),
strategy: group.cacheConfig.strategy || 'performance',
maxSize: group.cacheConfig.maxSize,
maxAge: parseDurationToMs(group.cacheConfig.maxAge),
Expand Down Expand Up @@ -123,11 +108,19 @@ function matches(file: string, patterns: {positive: boolean, regex: RegExp}[]):
return res;
}

function urlToRegex(url: string, baseHref: string): string {
if (!url.startsWith('/') && url.indexOf('://') === -1) {
url = joinUrls(baseHref, url);
}

return globToRegex(url);
}

function joinUrls(a: string, b: string): string {
if (a.endsWith('/') && b.startsWith('/')) {
return a + b.substr(1);
} else if (!a.endsWith('/') && !b.startsWith('/')) {
return a + '/' + b;
}
return a + b;
}
}

0 comments on commit c383b1a

Please sign in to comment.