refactor: move common logic to server

This commit is contained in:
Pooya Parsa 2020-11-03 21:26:27 +01:00
parent cbae59a88b
commit d441d79c6c
3 changed files with 50 additions and 22 deletions

View File

@ -16,6 +16,8 @@ const renderer = createRenderer(server, {
})
export async function render (url) {
const start = process.hrtime()
const ssrContext: any = {
url,
runtimeConfig: {
@ -26,13 +28,26 @@ export async function render (url) {
const rendered = await renderer.renderToString(ssrContext)
const state = `<script>window.__NUXT__ = ${devalue(ssrContext.payload)}</script>`
const html = `<div id="__nuxt">${rendered.html}</div>`
const _html = `<div id="__nuxt">${rendered.html}</div>`
return htmlTemplate({
const html = htmlTemplate({
HTML_ATTRS: '',
HEAD_ATTRS: '',
BODY_ATTRS: '',
HEAD: rendered.renderResourceHints() + rendered.renderStyles(),
APP: html + state + rendered.renderScripts()
APP: _html + state + rendered.renderScripts()
})
const end = process.hrtime(start)
const time = ((end[0] * 1e9) + end[1]) / 1e6
return {
html,
status: 200,
headers: {
'Content-Type': 'text/html;charset=UTF-8',
'X-Nuxt-Coldstart': global._coldstart + 'ms',
'X-Nuxt-ResponseTime': time + 'ms'
}
}
}

View File

@ -1,9 +1,23 @@
// @ts-ignore
import { render } from '~runtime/server'
render(process.argv[2] || '/')
.then(html => console.log(html))
.catch((err) => {
console.error(err)
process.exit(1)
})
const debug = (label, ...args) => console.debug(`> ${label}:`, ...args)
async function main () {
const url = process.argv[2] || '/'
debug('URL', url)
const { html, status, headers } = await render(url)
debug('Status', status)
for (const header in headers) {
debug(header, headers[header])
}
console.log('\n', html)
}
main().catch((err) => {
console.error(err)
process.exit(1)
})

View File

@ -1,18 +1,17 @@
// @ts-ignore
import { render } from '~runtime/server'
module.exports = (req, res) => {
const start = process.hrtime()
render(req.url).then((html) => {
const end = process.hrtime(start)
const time = ((end[0] * 1e9) + end[1]) / 1e6
// @ts-ignore
res.setHeader('X-Nuxt-Coldstart', global._coldstart + 'ms')
res.setHeader('X-Nuxt-Responsetime', time + 'ms')
module.exports = async (req, res) => {
try {
const { html, status, headers } = await render(req.url, { req, res })
for (const header in headers) {
res.setHeadeer(header, headers[header])
}
res.status(status)
res.end(html)
}).catch((err) => {
console.error(err)
res.end('Error: ' + err)
})
} catch (error) {
console.error(error)
res.status(500)
res.end('Internal Error: ' + error)
}
}