@@ -4,6 +4,7 @@ const LRU = require('lru-cache')
44const express = require ( 'express' )
55const favicon = require ( 'serve-favicon' )
66const compression = require ( 'compression' )
7+ const microcache = require ( 'route-cache' )
78const resolve = file => path . resolve ( __dirname , file )
89const { createBundleRenderer } = require ( 'vue-server-renderer' )
910
@@ -65,18 +66,13 @@ app.use('/public', serve('./public', true))
6566app . use ( '/manifest.json' , serve ( './manifest.json' , true ) )
6667app . use ( '/service-worker.js' , serve ( './dist/service-worker.js' ) )
6768
68- // 1-second microcache.
69- // https://www.nginx.com/blog/benefits-of-microcaching-nginx/
70- const microCache = LRU ( {
71- max : 100 ,
72- maxAge : 1000
73- } )
74-
7569// since this app has no user-specific content, every page is micro-cacheable.
7670// if your app involves user-specific content, you need to implement custom
7771// logic to determine whether a request is cacheable based on its url and
7872// headers.
79- const isCacheable = req => useMicroCache
73+ // 1-second microcache.
74+ // https://www.nginx.com/blog/benefits-of-microcaching-nginx/
75+ app . use ( microcache . cacheSeconds ( 1 , ( ) => useMicroCache ) )
8076
8177function render ( req , res ) {
8278 const s = Date . now ( )
@@ -88,26 +84,15 @@ function render (req, res) {
8884 if ( err . url ) {
8985 res . redirect ( err . url )
9086 } else if ( err . code === 404 ) {
91- res . status ( 404 ) . end ( '404 | Page Not Found' )
87+ res . status ( 404 ) . send ( '404 | Page Not Found' )
9288 } else {
9389 // Render Error Page or Redirect
94- res . status ( 500 ) . end ( '500 | Internal Server Error' )
90+ res . status ( 500 ) . send ( '500 | Internal Server Error' )
9591 console . error ( `error during render : ${ req . url } ` )
9692 console . error ( err . stack )
9793 }
9894 }
9995
100- const cacheable = isCacheable ( req )
101- if ( cacheable ) {
102- const hit = microCache . get ( req . url )
103- if ( hit ) {
104- if ( ! isProd ) {
105- console . log ( `cache hit!` )
106- }
107- return res . end ( hit )
108- }
109- }
110-
11196 const context = {
11297 title : 'Vue HN 2.0' , // default title
11398 url : req . url
@@ -116,10 +101,7 @@ function render (req, res) {
116101 if ( err ) {
117102 return handleError ( err )
118103 }
119- res . end ( html )
120- if ( cacheable ) {
121- microCache . set ( req . url , html )
122- }
104+ res . send ( html )
123105 if ( ! isProd ) {
124106 console . log ( `whole request: ${ Date . now ( ) - s } ms` )
125107 }
0 commit comments