Search code examples
apicachingdynamicangular-pwangsw-config

In Angular PWA How to Cache the API request( with paramter ) dynamically instead of manually adding each and every url in ngsw-config.json


I have some API like https://api-******y?apikey=sX4&q=london, Where q=london is a parameter that will keep changing, So how can i add this URL in the list of urls in ngsw-config.json file

"dataGroups": [
    {
      "name": "api-performance",
      "urls": [
        "https://api-***************y?apikey=sX******4&q=london",
        "https://api-***************y?apikey=sX******4&q=manchester",
        "https://api-***************y?apikey=sX******4&q=birmingham"
      ],
      "cacheConfig": {
        "strategy": "performance",
        "maxSize": 100,
        "maxAge": "3d"
      }
    },

I have two doubts:

  1. Instead of adding same url again and again for all different parameters like london/manchester/birmingham is there a way that i can just add the base URL without parameter and it will store the responses for all different parameters when user will search for it?

  2. Instead of adding the URL's manually, the URL's response should be stored dynamically when the user has searched for it when he was online. I mean i will initially not add any URL in list in the ngsw-config.json file, BUT when user has requested for that url, its response automatically get stored in cache.


Solution

  • I got this one, Its actually a little stupid of me to think that i have to give the complete url in the ngsw-config.json file, Actually we just can simply give the base url, we neither have to give the apiKey parameter nor any other parameter like london/manchester/birmingham, ngsw.json file in dist folder after the build, stores the url as patterns, it just matches the base url and stores all the queries with all different parameters made to that url by user. above code can re-written like below. it will work fine by caching the data for all the stores london/manchester/birmingham, whenever user searches for them.

    "dataGroups": [
        {
          "name": "api-performance",
          "urls": [
            "https://api-***************y
          ],
          "cacheConfig": {
            "strategy": "performance",
            "maxSize": 100,
            "maxAge": "3d"
          }
        },