1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00
next.js/server/render.js

187 lines
5.1 KiB
JavaScript
Raw Normal View History

2016-10-19 12:58:08 +00:00
import { join } from 'path'
2016-10-05 23:52:50 +00:00
import { createElement } from 'react'
import { renderToString, renderToStaticMarkup } from 'react-dom/server'
import send from 'send'
import fs from 'mz/fs'
import accepts from 'accepts'
import mime from 'mime-types'
2016-10-15 19:49:42 +00:00
import requireModule from './require'
import resolvePath from './resolve'
import readPage from './read-page'
import { Router } from '../lib/router'
2016-12-16 18:42:40 +00:00
import Head, { defaultHead } from '../lib/head'
2016-10-05 23:52:50 +00:00
import App from '../lib/app'
export async function render (req, res, pathname, query, opts) {
const html = await renderToHTML(req, res, pathname, opts)
sendHTML(res, html, req.method)
}
export function renderToHTML (req, res, pathname, query, opts) {
return doRender(req, res, pathname, query, opts)
}
export async function renderError (err, req, res, pathname, query, opts) {
const html = await renderErrorToHTML(err, req, res, query, opts)
sendHTML(res, html, req.method)
}
export function renderErrorToHTML (err, req, res, pathname, query, opts = {}) {
return doRender(req, res, pathname, query, { ...opts, err, page: '_error' })
}
async function doRender (req, res, pathname, query, {
err,
page,
buildId,
2016-10-10 04:24:30 +00:00
dir = process.cwd(),
dev = false,
2016-10-15 19:49:42 +00:00
staticMarkup = false
2016-10-10 04:24:30 +00:00
} = {}) {
page = page || pathname
2016-12-16 18:42:40 +00:00
let [Component, Document] = await Promise.all([
requireModule(join(dir, '.next', 'dist', 'pages', page)),
2016-12-16 18:42:40 +00:00
requireModule(join(dir, '.next', 'dist', 'pages', '_document'))
])
Component = Component.default || Component
Document = Document.default || Document
const ctx = { err, req, res, pathname, query }
2016-10-05 23:52:50 +00:00
const [
props,
component,
errorComponent
] = await Promise.all([
Component.getInitialProps ? Component.getInitialProps(ctx) : {},
readPage(join(dir, '.next', 'bundles', 'pages', page)),
readPage(join(dir, '.next', 'bundles', 'pages', '_error'))
])
2016-10-05 23:52:50 +00:00
// the response might be finshed on the getinitialprops call
if (res.finished) return
2016-12-16 18:42:40 +00:00
const renderPage = () => {
2016-10-06 02:42:55 +00:00
const app = createElement(App, {
Component,
props,
err,
router: new Router(pathname, query)
2016-10-06 02:42:55 +00:00
})
const render = staticMarkup ? renderToStaticMarkup : renderToString
let html
let head
try {
html = render(app)
} finally {
head = Head.rewind() || defaultHead()
}
2016-12-16 18:42:40 +00:00
return { html, head }
}
2016-10-06 02:42:55 +00:00
2016-12-16 18:42:40 +00:00
const docProps = await Document.getInitialProps({ ...ctx, renderPage })
2016-10-05 23:52:50 +00:00
const doc = createElement(Document, {
2016-12-16 18:42:40 +00:00
__NEXT_DATA__: {
2016-10-09 09:50:41 +00:00
component,
errorComponent,
2016-10-09 09:50:41 +00:00
props,
pathname,
query,
buildId,
err: (err && dev) ? errorToJSON(err) : null
2016-10-09 09:50:41 +00:00
},
2016-10-10 04:24:30 +00:00
dev,
2016-10-28 14:38:24 +00:00
staticMarkup,
2016-12-16 18:42:40 +00:00
...docProps
2016-10-05 23:52:50 +00:00
})
return '<!DOCTYPE html>' + renderToStaticMarkup(doc)
}
export async function renderJSON (req, res, page, { dir = process.cwd() } = {}) {
const pagePath = await resolvePath(join(dir, '.next', 'bundles', 'pages', page))
return serveStaticWithGzip(req, res, pagePath)
2016-10-05 23:52:50 +00:00
}
2016-10-10 04:24:30 +00:00
export async function renderErrorJSON (err, req, res, { dir = process.cwd(), dev = false } = {}) {
const component = await readPage(join(dir, '.next', 'bundles', 'pages', '_error'))
sendJSON(res, {
component,
err: err && dev ? errorToJSON(err) : null
}, req.method)
}
export function sendHTML (res, html, method) {
if (res.finished) return
res.setHeader('Content-Type', 'text/html')
res.setHeader('Content-Length', Buffer.byteLength(html))
res.end(method === 'HEAD' ? null : html)
}
export function sendJSON (res, obj, method) {
if (res.finished) return
const json = JSON.stringify(obj)
res.setHeader('Content-Type', 'application/json')
res.setHeader('Content-Length', Buffer.byteLength(json))
res.end(method === 'HEAD' ? null : json)
}
function errorToJSON (err) {
2016-10-19 12:41:45 +00:00
const { name, message, stack } = err
const json = { name, message, stack }
if (name === 'ModuleBuildError') {
// webpack compilation error
const { module: { rawRequest } } = err
json.module = { rawRequest }
}
return json
}
export async function serveStaticWithGzip (req, res, path) {
const encoding = accepts(req).encodings(['gzip'])
if (encoding !== 'gzip') {
return serveStatic(req, res, path)
}
const gzipPath = `${path}.gz`
try {
// We need to check the existance of the gzipPath.
// Getting `ENOENT` error from the `serveStatic` is inconsistent and
// didn't work on all the cases.
//
// And this won't give us a race condition because we know that
// we don't add gzipped files at runtime.
await fs.stat(gzipPath)
} catch (ex) {
New test setup (#640) * Use jest-cli instead of gulp plugin. * Use jest-cli instead of gulp plugin. * Move fixtures into the examples dir. * Move test code of example app to the basic example. * Add isolated tests for server/resolve * Allow tests to use cheerio. * Use portfinder to get a unique port. * Move back integration tests into the example dir. * Introduce next-test-utils. * Remove gulp-jest * Add coveralls support. * Use transpiled version of code in dist. This is to make sure same file gets covered by both unit/isolated tests and integration tests. * Add support for source maps. * Use code from dist always. * Use nyc to stop instrument. * Add integration test suite for production usage. * Use jest-cli. * Add support for running e2e tests. * Check gzipPath with fs.stat before serving Otherwise, serve package might throw issues other than ENOENT * Install chromedriver with npm install. * Install chrome on travis-ci. * Add --forceExit to Jest. * Run tests only on Node v6. That's because selenium-webdriver only supports Node 6 LTS. * Use chromedriver NPM module to install chromedriver. * Use wd as the webdriver client. * Run chromedriver before tests. * Run travis for both node 4 and 6 * Remove unwanted npm install script. * Move some common text utilities to next-test-utils * Add lint checks and testing in npm prepublish hook. * Use npm on travis-ci. We are having some caching issues with yarn and chromedriver. * Make tests work on windows.\n But chromedriver doesn't work. * Clean up dependencies. * Run chromedriver in background without any tools. * Fix a typo in the code. * Use ES6 features used in node4 inside the gulpfile. * Add some comments. * Add support for running in windows. * Stop chromedriver properly on windows. * Fix typos.
2017-01-12 04:14:49 +00:00
// Handles the error thrown by fs.stat
if (ex.code === 'ENOENT') {
// Seems like there's no gzipped file. Let's serve the uncompressed file.
return serveStatic(req, res, path)
}
throw ex
}
const contentType = mime.lookup(path) || 'application/octet-stream'
res.setHeader('Content-Type', contentType)
res.setHeader('Content-Encoding', 'gzip')
return serveStatic(req, res, gzipPath)
}
export function serveStatic (req, res, path) {
return new Promise((resolve, reject) => {
send(req, path)
.on('error', reject)
.pipe(res)
.on('finish', resolve)
})
}