5
votes

I use Angular 5.2.7 with Angular Service Worker 5.2.7.

I want to cache webservices calls. So, I've got with this config in my ngsw-config.json, for dataGroups :

"dataGroups": [{
  "name": "tasks-users-api",
  "urls": ["/api", "/rest"],
  "cacheConfig": {
    "strategy": "freshness",
    "maxSize": 20000,
    "maxAge": "1h",
    "timeout": "5s"
  }
}]

I try to cache this two URLs : https://randomuser.me/api/?results=20 ---> It's OK https://test.moodlecloud.com/webservice/rest/server.php ---> It's KO

The first one is cached as expected. It's a simple GET service. The second one isn't. It's a POST service with a form data sent as payload.

Any idea of what is wrong with that ?

1
Why would it cache a POST? They aren't idempotent; if you make two requests, you'd expect two resources to be created. Caching would completely break that. - jonrsharpe
@jonrsharpe That's the purpose of offline cache. That's also why he uses the 'freshness' strategy so that the service worker tries to fetch the resource and fallback if it can't fetch it. - Ploppy
Ploppy is right but jonrsharpe get a point. I've never had to handle a POST request SW caching before, and never think about it. Now, after some research in good directions, it seems that SW implementation doesn't allow POST requests to be stored : stackoverflow.com/questions/35270702/… - fabienbranchel
Guys it is possible to read the post request by intercepting the fetch event in the service worker. You can store that information however you want, but indexedDB is an easy option for me. Check the above mentioned stackoverflow question, I posted an example today - Roman Gherta

1 Answers

5
votes

Service Worker API does not allow POST/PUT requests.

In this blog article it is showed an example on how you can use Indexed Db (as suggested by Roman Gherta) to store POST/PUT requests.

This solution is also suggested on Mozilla resource.