0.1.2 • Published 5 years ago

nuxt-cache-payload v0.1.2

Weekly downloads
1
License
MIT
Repository
github
Last release
5 years ago

🗄 nuxt-cache-payload

npm version MIT License CircleCI Maintainability Dependencies devDependencies

What's this

This is a module to generate cache file for nuxt generateed sites.

By default, Nuxt provides payload object from config.generate.routes() only on first one page of the session. Other pages that are navigated programmably such as by <nuxt-link> cannot get payload objects.

// nuxt.config.js
module.exports = {
  generate: {
    routes() {
      return [
        {
          route: '/dynamic/routed/page',
          payload: await fetchPagePayload(), // Get something from network resource, etc.
        }
      ];
    }
  }
};

// /pages/dynamic/routed/_page.vue
exports default {
  async asyncData( { payload } ) {
    if( payload ) return { payload }; // For as first one page (production) this one is used.
    else return { payload: async fetchPagePayload() }; // For other pages...
  }
};

If fetchPagePayload() contains heavy process (Ex: with long latency), it delays page loading.

This modules generate cache files of payload object from config.generate() and make it to be able to reduce payload generate requests.

Usage

Install with npm install nuxt-cache-payload and register in nuxt.config.js.

// /pages/dynamic/routed/_page.vue
exports default {
  async asyncData( { getPayload, payload, route } ) {
    return {
      payload:    payload                         // For as the first one page
               || await getPayload( route.path )  // For as the 2nd (or later) page: fetch cached payload
               || await fetchPagePayload()        // Fallback & for development mode
    };
  }
};

Module generate cache files with nuxt generate and it can be fetched by using context.getPayload() inside asyncData().

Note: Cache files will be generated only with nuxt generate and context.getPayload() will returns null when called in non-static environment. You should fetch payload data manually from original source in devMode or at server-side rendering.

Options

// nuxt.config.js
module.exports = {
  modules: [
    [ 'nuxt-cache-payload', {

      // Custom file for cache files (optional).
      // Default: '_payload.${randomHash}.json'
      filename: 'cachefile.json',

      // Encoding of cache files (optional).
      // Default: 'utf8'
      encoding: 'utf8',

    } ];
  ]
};

Contributing

Pull requests or feature requests are welcome. Please submit them from GitHub.

License

MIT License: Copyright (c) Kazumi Inada