Monday, 15 May 2017

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?



via ppshein

No comments:

Post a Comment