legeneek / nuxt-cache-module

nuxt page cache module
8 stars 0 forks source link

nice simple code but can you share your implementation of your cache setter/getter ? #1

Closed vesper8 closed 4 years ago

vesper8 commented 4 years ago

The only other popular nuxt cache package is https://github.com/arash16/nuxt-ssr-cache and it seems abandonned and according to the latest issues it isn't even working anymore

yours sounds like a good potential replacement but it's my understanding you're only providing half the solution here? The part where we get/set into memory/redis/memcache/file store is up to the user to provide?

I'm sure you've already made use of your package so it would be nice if you could share the other part that you're using.. whether you've chosen to use redis or a file store. Or perhaps you have other built-in options such as a max number of pages that can be saved etc

Would be great if you could share this code too in the form of an example in the readme or another repository ?

Many thanks either way

legeneek commented 4 years ago

yes, the cache is up to the user to provide.

I use redis as my cache, the example below use koa and ioredis. ioredis implement the get and set method I use 😄 .

// server.js
const Redis = require('ioredis')

const redisClient = await new Promise((resolve, reject) => {
    const client = new Redis({
      host: config.redis.host,
      port: config.redis.port,
      connectTimeout: 10000,
      maxRetriesPerRequest: 1,
      keyPrefix: '',
      retry_strategy (times) {
        // reconnect after
        return 100
      }
    })
    client.on('connect', () => {
      resolve(client)
    })
    client.on('error', (e) => {
      reject(e)
    })
  }).catch((e) => {
  })

 // each time restart server will flush the page cache and set the right version(eg:commit hash)
 // not a good solution,  should do it in pre-publish script
 if (redisClient) {
    redisClient.sendCommand(new Redis.Command('flushall'))
   // the appVersion and youAppVersionKey also used in nuxt.config.js
    redisClient.set(youAppVersionKey, appVersion)
 }

 // inject cache to ctx in server app middleware, so the cache builder can get it.
 app.use(async (ctx, next) => {
    if (redisClient) {
      ctx.cache = redisClient
    }
    await next()
 })
 // nuxt.config.js
['~modules/cache', {
      hashKey: true,
      keyBuilder: (route, context) => {
      },
      expireTime: 1800,
      versionKey: youAppVersionKey,
      appVersion: appVersion,
      hitHeader: 'x-page-cache',
      cacheBuilder: (context) => {
        // get cache from ctx
        return context.req && context.req.ctx.cache
      },
      shouldCache: (route, context) => {
          const r = route.split(/[?#]/)[0]
          // I use regex to check the route, only home page is allowed to cache
          if (pageRegex.home.test(r)) {
            return true
          }
      },
      shouldSave: (context) => {
      }
    }]

hope useful, will update readme later