Search code examples
javascriptcachingfrontendservice-workerweb-worker

Cache.match(request) returns undefined in service-worker for JSONP requests


Below you can see my first attempt at creating a service-worker and the problem with this code is that it never returns cached response since cache.match(request) in addUrlToCache function is always returning undefined. Does anyone have any ideas as to why it's not finding cached requests?

import API from 'top-secret'

const PHOTOS_CACHE = 'photos-cache'
const OBJECTS_CACHE = 'objects-cache'

const urlCacheData = [
  {
    cacheKey: OBJECTS_CACHE,
    url: API.apiUrlGetObjects
  },
  {
    cacheKey: PHOTOS_CACHE,
    url: API.apiUrlGetPhotos
  }
]

function addUrlToCache (request, cacheKey) {
  return caches
    .open(cacheKey)
    .then(cache => cache.match(request))
    .then(cachedResponse => {
      if (cachedResponse) {
        return cachedResponse
      }

      return fetch(request).then(response => {
        caches.open(cacheKey).then(cache => cache.put(request, response))

        return response.clone()
      })
    })
}

function clearCache () {
  return caches.keys().then(cacheNames => {
    const promisesToDeleteCache = cacheNames.map(cacheName =>
      caches.delete(cacheName)
    )
    return Promise.all(promisesToDeleteCache)
  })
}

self.addEventListener('activate', event => {
  event.waitUntil(clearCache())
})

self.addEventListener('fetch', event => {
  const urlToCache = urlCacheData.find(item =>
    event.request.url.includes(item.url)
  )

  if (urlToCache) {
    event.respondWith(
      addUrlToCache(event.request, urlToCache.cacheKey)
    )
  }
})

Solution

  • I've just figured out that the problem was that I had JSONP requests with random callback values like bla-bla/api?callback=jsonp_randomNumber, so url would be different every time I make a request because of the random number thing, that's why cache.match check wouldn't work.

    I fixed it by hardcoding callback value in the config of the jsonp library that I used (jsonp-fetch in my case).