Skip to content

Commit e7bc06b

Browse files
committed
fix(sw.js): fix cache store
fix cache store that cache svery request on current page
1 parent f78644b commit e7bc06b

File tree

3 files changed

+55
-182
lines changed

3 files changed

+55
-182
lines changed

.travis.yml

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,6 @@ sudo: false
22
language: node_js
33
node_js:
44
- "10"
5-
branches:
6-
only:
7-
- master
85
notifications:
96
email: false
107

public/sw.js

Lines changed: 55 additions & 167 deletions
Original file line numberDiff line numberDiff line change
@@ -1,180 +1,68 @@
1-
/* eslint-disable @typescript-eslint/no-use-before-define */
2-
//This is the service worker with the Advanced caching
3-
4-
const CACHE = "pwabuilder-adv-cache";
5-
const precacheFiles = [
6-
/* Add an array of files to precache for your app */
7-
];
8-
9-
// TODO: replace the following with the correct offline fallback page i.e.: const offlineFallbackPage = "offline.html";
10-
const offlineFallbackPage = "ToDo-replace-this-name.html";
11-
12-
const networkFirstPaths = [
13-
/* Add an array of regex of paths that should go network first */
14-
// Example: /\/api\/.*/
15-
];
16-
17-
const avoidCachingPaths = [
18-
/* Add an array of regex of paths that shouldn't be cached */
19-
// Example: /\/api\/.*/
20-
/\/Images\/.*/,
21-
/\/free\/.*/,
22-
/\/bootstrap\/.*/,
23-
/\/user\/.*/,
24-
/\/ajax\/.*/,
25-
/\/repos\/.*/,
26-
/\/recaptcha\/.*/,
27-
/\/auth\/.*/,
28-
/\/socket.io\/.*/,
29-
/\/avatar\/.*/,
30-
/\/delete\/.*/,
31-
/\/create\/.*/,
32-
33-
"https://source.unsplash.com",
34-
"https://code.jquery.com/jquery-3.2.1.slim.min.js",
1+
const CACHE_NAME = "pwabuilder-adv-cache";
2+
const {INSTALL, FETCH} = {
3+
INSTALL: "install",
4+
FETCH: "fetch",
5+
};
6+
const URLS_TO_CACHE = [
7+
"./",
8+
"./dist/style.css",
9+
"./dist/App.bundle.js",
10+
"./sw.js",
11+
"./pwabuilder.js",
12+
"./manifest.json",
3513
"https://buttons.github.io/buttons.js",
3614
];
37-
38-
function pathComparer(requestUrl, pathRegEx) {
39-
return requestUrl.match(new RegExp(pathRegEx));
40-
}
41-
42-
function comparePaths(requestUrl, pathsArray) {
43-
if (requestUrl) {
44-
for (let index = 0; index < pathsArray.length; index++) {
45-
const pathRegEx = pathsArray[index];
46-
if (pathComparer(requestUrl, pathRegEx)) {
47-
return true;
48-
}
49-
}
15+
const preLoad = async () => {
16+
console.log("Installing web app");
17+
try {
18+
const cache = await caches.open(CACHE_NAME);
19+
const cachedUrls = cache.addAll(URLS_TO_CACHE);
20+
return cachedUrls;
21+
} catch (error) {
22+
console.error(error);
5023
}
24+
};
5125

52-
return false;
53-
}
54-
55-
self.addEventListener("install", function(event) {
56-
console.log("[PWA Builder] Install Event processing");
57-
58-
console.log("[PWA Builder] Skip waiting on install");
26+
self.addEventListener(INSTALL, event => {
5927
self.skipWaiting();
60-
61-
event.waitUntil(
62-
caches.open(CACHE).then(function(cache) {
63-
console.log("[PWA Builder] Caching pages during install");
64-
65-
return cache.addAll(precacheFiles).then(function() {
66-
if (offlineFallbackPage === "ToDo-replace-this-name.html") {
67-
return cache.add(
68-
new Response(
69-
"TODO: Update the value of the offlineFallbackPage constant in the serviceworker.",
70-
),
71-
);
72-
}
73-
74-
return cache.add(offlineFallbackPage);
75-
});
76-
}),
77-
);
78-
});
79-
80-
// Allow sw to control of current page
81-
self.addEventListener("activate", function(event) {
82-
console.log("[PWA Builder] Claiming clients for current page");
83-
event.waitUntil(self.clients.claim());
84-
});
85-
86-
// If any fetch fails, it will look for the request in the cache and serve it from there first
87-
self.addEventListener("fetch", function(event) {
88-
if (event.request.method !== "GET") return;
89-
90-
if (comparePaths(event.request.url, networkFirstPaths)) {
91-
networkFirstFetch(event);
92-
} else {
93-
cacheFirstFetch(event);
94-
}
28+
event.waitUntil(preLoad());
29+
console.log("installed latest version");
9530
});
9631

97-
function cacheFirstFetch(event) {
98-
event.respondWith(
99-
fromCache(event.request).then(
100-
function(response) {
101-
// The response was found in the cache so we responde with it and update the entry
102-
103-
// This is where we call the server to get the newest version of the
104-
// file to use the next time we show view
105-
event.waitUntil(
106-
fetch(event.request).then(function(response) {
107-
return updateCache(event.request, response);
108-
}),
109-
);
110-
111-
return response;
112-
},
113-
function() {
114-
// The response was not found in the cache so we look for it on the server
115-
return fetch(event.request)
116-
.then(function(response) {
117-
// If request was success, add or update it in the cache
118-
event.waitUntil(updateCache(event.request, response.clone()));
119-
120-
return response;
121-
})
122-
.catch(function(error) {
123-
// The following validates that the request was for a navigation to a new document
124-
if (event.request.destination !== "document" || event.request.mode !== "navigate") {
125-
return;
126-
}
127-
128-
console.log("[PWA Builder] Network request failed and no cache." + error);
129-
// Use the precached offline page as fallback
130-
return caches.open(CACHE).then(function(cache) {
131-
cache.match(offlineFallbackPage);
132-
});
133-
});
134-
},
135-
),
136-
);
137-
}
138-
139-
function networkFirstFetch(event) {
140-
event.respondWith(
141-
fetch(event.request)
142-
.then(function(response) {
143-
// If request was success, add or update it in the cache
144-
event.waitUntil(updateCache(event.request, response.clone()));
145-
return response;
146-
})
147-
.catch(function(error) {
148-
console.log("[PWA Builder] Network request Failed. Serving content from cache: " + error);
149-
return fromCache(event.request);
150-
}),
151-
);
152-
}
153-
154-
function fromCache(request) {
155-
// Check to see if you have it in the cache
156-
// Return response
157-
// If not in the cache, then return error page
158-
return caches.open(CACHE).then(function(cache) {
159-
return cache.match(request).then(function(matching) {
160-
if (!matching || matching.status === 404) {
161-
return Promise.reject("no-match");
32+
const makeNetWorkRequest = request =>
33+
new Promise(async (resolve, reject) => {
34+
try {
35+
const networkFetchResponse = await fetch(request);
36+
if (networkFetchResponse.status !== 404) {
37+
resolve(networkFetchResponse);
38+
} else {
39+
throw new Error("no resource found");
16240
}
163-
164-
return matching;
165-
});
41+
} catch (error) {
42+
console.error(error);
43+
reject(error);
44+
}
16645
});
167-
}
168-
169-
function updateCache(request, response) {
170-
if (!comparePaths(request.url, avoidCachingPaths)) {
171-
return caches.open(CACHE).then(function(cache) {
172-
return cache.put(request, response);
173-
});
46+
const returnFromCache = async request => {
47+
try {
48+
const cache = await caches.open(CACHE_NAME);
49+
const cacheItemMatchingNetworkRequest = await cache.match(request);
50+
if (!cacheItemMatchingNetworkRequest || cacheItemMatchingNetworkRequest.status == 404) {
51+
return cache.match("/");
52+
} else {
53+
return cacheItemMatchingNetworkRequest;
54+
}
55+
} catch (error) {
56+
console.error(error);
17457
}
175-
176-
return Promise.resolve();
177-
}
58+
};
59+
self.addEventListener(FETCH, event => {
60+
event.respondWith(
61+
makeNetWorkRequest(event.request).catch(() => {
62+
return returnFromCache(event.request);
63+
}),
64+
);
65+
});
17866

17967
// This is an event that can be fired from your page to tell the SW to update the offline page
18068
self.addEventListener("refreshOffline", function() {

src/app.ts

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -42,17 +42,13 @@ app.use(express.static(path.join(__dirname, "../public")));
4242
app.use(express.json());
4343
app.use(express.urlencoded({extended: true}));
4444

45-
const expiryDate = new Date(Date.now() + 60 * 60 * 1000); // 1 hour
4645
app.use(
4746
session({
4847
name: process.env.SESSION_NAME,
4948
secret: process.env.SECRET,
5049
resave: false,
5150
saveUninitialized: false,
5251
store: new MongoStore({mongooseConnection: mongoose.connection}),
53-
cookie: {
54-
expires: expiryDate,
55-
},
5652
}),
5753
);
5854

@@ -78,14 +74,6 @@ app.use("/auth", authRouter);
7874
app.get("*", function(req: express.Request, res: express.Response) {
7975
return res.status(404).redirect("/404");
8076
});
81-
// 500 - Any server error
82-
app.use(function(err: any, req: express.Request, res: express.Response, next: express.NextFunction) {
83-
res.status(err.status || 500);
84-
res.render("error", {
85-
message: err.message,
86-
error: {},
87-
});
88-
});
8977

9078
if (app.get("env") === "development") {
9179
app.use(errorHandler());

0 commit comments

Comments
 (0)