· 4 years ago · Jul 27, 2021, 11:18 AM
1async function handleRequest(event) {
2
3 const max_age = 2700
4
5 const request = event.request
6 const url = new URL(request.url);
7 const strUrl = url.toString();
8
9 //Check if the user is logged in
10 const cookie = getCookie(request, "islogged")
11 // User logged in
12 if (cookie) {
13 let response = await fetch(request);
14 return response;
15 }
16
17 // Read the user agent of the request
18 const ua = request.headers.get('user-agent');
19 let uaValue;
20
21 if (ua.match(/mobile/i)) {
22 uaValue = 'mobile';
23 } else {
24 uaValue = 'desktop';
25 }
26
27 // Construct a new response object which distinguishes the cache key by device
28 // type.
29 url.searchParams.set('ua', uaValue);
30 const newRequest = new Request(url, request);
31 const cacheUrl = new URL(newRequest.url)
32
33 // Construct the cache key from the cache URL
34 const cacheKey = new Request(cacheUrl.toString(), request)
35 const cache = caches.default
36
37 // Check whether the value is already available in the cache
38 // if not, you will need to fetch it from origin, and store it in the cache
39 // for future access
40 let response = await cache.match(cacheKey)
41
42 if (!response) {
43 // If not in cache, get it from origin
44 response = await fetch(newRequest)
45
46 // Must use Response constructor to inherit all of response's fields
47 response = new Response(response.body, response)
48
49 // Cache API respects Cache-Control headers. Setting s-max-age to 10
50 // will limit the response to be in cache for 10 seconds max
51
52 // Any changes made to the response here will be reflected in the cached value
53 response.headers.append("Cache-Control", "s-maxage=" + max_age)
54 response.headers.append("Cache-Control", "max-age=0")
55
56 // Store the fetched response as cacheKey
57 // Use waitUntil so you can return the response without blocking on
58 // writing to cache
59 event.waitUntil(cache.put(cacheKey, response.clone()))
60 }
61 return response
62}
63
64addEventListener("fetch", event => {
65 try {
66 const request = event.request
67 return event.respondWith(handleRequest(event))
68 } catch (e) {
69 return event.respondWith(new Response("Error thrown " + e.message))
70 }
71})
72
73
74/**
75 * Gets the cookie with the name from the request headers
76 * @param {Request} request incoming Request
77 * @param {string} name of the cookie to get
78 */
79function getCookie(request, name) {
80 let result = ""
81 const cookieString = request.headers.get("Cookie")
82 if (cookieString) {
83 const cookies = cookieString.split(";")
84 cookies.forEach(cookie => {
85 const cookiePair = cookie.split("=", 2)
86 const cookieName = cookiePair[0].trim()
87 if (cookieName === name) {
88 const cookieVal = cookiePair[1]
89 result = cookieVal
90 }
91 })
92 }
93 return result
94}