We're storing JSON data in the cache - but that only applies to HTTP GET
requests - and not to POST
or DELETE
requests.
We'll add a fetch
event listener to the service worker, where we can intercept all fetch requests in our app. We'll forward them to the server - but if they fail, then we'll return an error back to the app.
In the app, we can detect that error, and respond by showing an alert that the functionality isn't available in offline mode.
Instructor: [00:00] In sw.js we have registered a route to cache the JSON coming from the server, but HTTP post requests aren't cached by the service worker. Let's add an event listener here to listen for any fetch requests coming from the app. The event callback takes an event as an argument.
[00:23] Now get requests are handled by other routes. Let's just check if the request is a post or a delete. We have to have a response here, so let's call event.respondWith. Inside of that we can do something with the request.
[00:41] In the normal case where the network is available we will just call fetch here and pass the request directly from the event, when we're offline though that will fail. We can have a cache here and now we're able to respond with anything that we'd like.
[00:57] We could pull something from the cache like an offline error message or we could generate a new response and pass in some JSON with an error message. In a real app we could do some other things here as well.
[01:09] Like store the post data in a local storage for later or have more advanced error messages based on a type of action that the user is trying to do. Now back in app.js we're expecting that for many items that JSON call we'll get an array of items back. Now it's possible to get an array of items in the OK case or an object with an error in the network offline case.
[01:34] Let's add an if statement for the error case and just use an alert to show the error message for now in both the post and delete methods. Now we can build and serve that. In the browser when the app is online, online posts and delete still work.
[02:03] If we switch to offline and try a post or a delete, we get the alert that the functionality isn't available while offline. We could have also handled this in the fetch code itself, but doing it in the service worker allows us to respond the same way across all posts and deletes in our entire application.
self.addEventListener('fetch', event => { if(event.request.method === "POST" || event.request.method === "DELETE") { event.respondWith( fetch(event.request).catch(err => { return new Response( JSON.stringify({ error: "This action disabled while app is offline" }), { headers: { 'Content-Type': 'application/json' } } ) }) ) } })
The code above appears to be capturing all types of exceptions/errors and returning them as
offline
errors?