Pyae Phyoe Shein
Pyae Phyoe Shein

Reputation: 13837

Cache API and images from backend server in sw-precache with gulp

I'm very new to use sw-precache with gulp in my app. I've created web app done by angularjs and fetch information from our backend nodejs application. At that application, I've added sw-precache feature to make offline first application.

one of api from backend, company images will be embedded as follow:

https://www.myserver.com/api/getcompany

{"company": [
    {"id": 1, "img": "https://myserver.com/images/img.jpg"},
    {"id": 2, "img": "https://myserver.com/images/img.jpg"}
]}

Here is my coding to use sw-preache with gulp to generate service-worker file.

gulp.task('generate-service-worker', function(callback) {
  var path = require('path');
  var swPrecache = require('sw-precache');
  var rootDir = 'dist';

  swPrecache.write(path.join(rootDir, 'sw.js'), {
    staticFileGlobs: [rootDir + '/**/*.{js,html,css,png,jpg,gif}'],
    stripPrefix: rootDir,
    runtimeCaching: [{
      urlPattern: /^https:\/\/myserver.com\.com\/api/,
      handler: 'networkFirst'
    }, {
      urlPattern: /\/api\//,
      handler: 'fastest',
      options: {
          cache: {
            maxEntries: 10,
            name: 'api-cache-01'
          }
      }
    }]
  }, callback);
});

Please let me know above coding is correct way to cache API and please let me know how to cache images from URL in gulp file?

Upvotes: 1

Views: 721

Answers (1)

Jeff Posnick
Jeff Posnick

Reputation: 56124

Your two urlPatterns/^https:\/\/myserver.com\.com\/api/ and /\/api\//, look like they'd end up handling the same sort of requests (though the one listed first in the array will take precedence).

It sounds like you have two different types requests that you'd like to apply runtime caching logic to, so let's treat them separately.

First, for your /api/ requests, figure out whether you're okay with a stale response (in which case, use fastest) or whether you always need a fresh response.

Second, for your /image/ requests, figure out if you expect that image at a given URL will event change or not (if it won't change, use cacheFirst).

You'll end up with a configuration that looks something like:

runtimeCaching: [{
  urlPattern: new RegExp('/api/'),
  handler: 'fastest' // Alternatively, 'networkFirst'.
}, {
  urlPattern: new RegExp('/images/'),
  handler: 'cacheFirst', // Alternatively, 'fastest'.
  options: {
    cache: {
      maxEntries: 50, // Or whatever upper limit you want.
      name: 'images'
    }
  }
}]

Upvotes: 1

Related Questions