const express = require('express')
const next = require('next')
const LRUCache = require('lru-cache')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dir: '.', dev })
const handle = app.getRequestHandler()

// This is where we cache our rendered HTML pages
const ssrCache = new LRUCache({
  max: 100,
  maxAge: 1000 * 60 * 60 // 1hour
})

app.prepare()
.then(() => {
  const server = express()

  // Use the `renderAndCache` utility defined below to serve pages
  server.get('/', (req, res) => {
    renderAndCache(req, res, '/')
  })

  server.get('/blog/:id', (req, res) => {
    const queryParams = { id: req.params.id }
    renderAndCache(req, res, '/blog', queryParams)
  })

  server.get('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(3000, (err) => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})

function renderAndCache (req, res, pagePath, queryParams) {
  // If we have a page in the cache, let's serve it
  if (ssrCache.has(req.url)) {
    console.log(`CACHE HIT: ${req.url}`)
    res.send(ssrCache.get(req.url))
    return
  }

  // If not let's render the page into HTML
  app.renderToHTML(req, res, pagePath, queryParams)
    .then((html) => {
      // Let's cache this page
      console.log(`CACHE MISS: ${req.url}`)
      ssrCache.set(req.url, html)

      res.send(html)
    })
    .catch((err) => {
      app.renderError(err, req, res, pagePath, queryParams)
    })
}

@@ -881,16 +881,224 @@
  %7D)%0A%7D)%0A%0A
+/*%0A * NB: make sure to modify this to take into account anything that should trigger%0A * an immediate page change (e.g a locale stored in req.session)%0A */%0Afunction getCacheKey (req) %7B%0A  return %60$%7Breq.url%7D%60%0A%7D%0A%0A
 function
@@ -1149,16 +1149,48 @@
 rams) %7B%0A
+  const key = getCacheKey(req)%0A%0A
   // If 
@@ -1252,23 +1252,19 @@
 che.has(
-req.url
+key
 )) %7B%0A   
@@ -1286,31 +1286,27 @@
 ACHE HIT: $%7B
-req.url
+key
 %7D%60)%0A    res.
@@ -1323,23 +1323,19 @@
 che.get(
-req.url
+key
 ))%0A    r
@@ -1527,23 +1527,19 @@
 MISS: $%7B
-req.url
+key
 %7D%60)%0A    
@@ -1553,23 +1553,19 @@
 che.set(
-req.url
+key
 , html)%0A

document way to configure cache key (#1133)