Commit 2f479ef9 authored by Evan You's avatar Evan You

simplify usage

parent 89d33b6b
...@@ -83,7 +83,7 @@ app.get('*', (req, res) => { ...@@ -83,7 +83,7 @@ app.get('*', (req, res) => {
res.setHeader("Content-Type", "text/html") res.setHeader("Content-Type", "text/html")
res.setHeader("Server", serverInfo) res.setHeader("Server", serverInfo)
const errorHandler = err => { const handleError = err => {
if (err && err.code === 404) { if (err && err.code === 404) {
res.status(404).end('404 | Page Not Found') res.status(404).end('404 | Page Not Found')
} else { } else {
...@@ -98,31 +98,25 @@ app.get('*', (req, res) => { ...@@ -98,31 +98,25 @@ app.get('*', (req, res) => {
if (cacheable) { if (cacheable) {
const hit = pageCache.get(req.url) const hit = pageCache.get(req.url)
if (hit) { if (hit) {
if (!isProd) {
console.log(`cache hit!`) console.log(`cache hit!`)
}
return res.end(hit) return res.end(hit)
} }
} }
const context = { url: req.url } renderer.renderToString({ url: req.url }, (err, html) => {
const stream = renderer.renderToStream(context) if (err) {
return handleError(err)
}
res.end(html)
if (cacheable) { if (cacheable) {
let content = '' pageCache.set(req.url, html)
stream
.on('data', chunk => {
content += chunk.toString()
})
.on('end', () => {
pageCache.set(req.url, content)
})
} }
if (!isProd) {
stream
.on('error', errorHandler)
.on('end', () => {
console.log(`whole request: ${Date.now() - s}ms`) console.log(`whole request: ${Date.now() - s}ms`)
}
}) })
.pipe(res)
}) })
const port = process.env.PORT || 8080 const port = process.env.PORT || 8080
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment