@@ -4,6 +4,7 @@ const LRU = require('lru-cache')
4
4
const express = require ( 'express' )
5
5
const favicon = require ( 'serve-favicon' )
6
6
const compression = require ( 'compression' )
7
+ const microcache = require ( 'route-cache' )
7
8
const resolve = file => path . resolve ( __dirname , file )
8
9
const { createBundleRenderer } = require ( 'vue-server-renderer' )
9
10
@@ -65,18 +66,13 @@ app.use('/public', serve('./public', true))
65
66
app . use ( '/manifest.json' , serve ( './manifest.json' , true ) )
66
67
app . use ( '/service-worker.js' , serve ( './dist/service-worker.js' ) )
67
68
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
-
75
69
// since this app has no user-specific content, every page is micro-cacheable.
76
70
// if your app involves user-specific content, you need to implement custom
77
71
// logic to determine whether a request is cacheable based on its url and
78
72
// 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 ) )
80
76
81
77
function render ( req , res ) {
82
78
const s = Date . now ( )
@@ -88,26 +84,15 @@ function render (req, res) {
88
84
if ( err . url ) {
89
85
res . redirect ( err . url )
90
86
} else if ( err . code === 404 ) {
91
- res . status ( 404 ) . end ( '404 | Page Not Found' )
87
+ res . status ( 404 ) . send ( '404 | Page Not Found' )
92
88
} else {
93
89
// Render Error Page or Redirect
94
- res . status ( 500 ) . end ( '500 | Internal Server Error' )
90
+ res . status ( 500 ) . send ( '500 | Internal Server Error' )
95
91
console . error ( `error during render : ${ req . url } ` )
96
92
console . error ( err . stack )
97
93
}
98
94
}
99
95
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
-
111
96
const context = {
112
97
title : 'Vue HN 2.0' , // default title
113
98
url : req . url
@@ -116,10 +101,7 @@ function render (req, res) {
116
101
if ( err ) {
117
102
return handleError ( err )
118
103
}
119
- res . end ( html )
120
- if ( cacheable ) {
121
- microCache . set ( req . url , html )
122
- }
104
+ res . send ( html )
123
105
if ( ! isProd ) {
124
106
console . log ( `whole request: ${ Date . now ( ) - s } ms` )
125
107
}
0 commit comments