Instructor: 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.
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.
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.
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.
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.
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.
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.