From 66b224ad26cf4d172becdaf6203fd09ed3303888 Mon Sep 17 00:00:00 2001 From: nkzawa Date: Thu, 6 Oct 2016 16:06:55 +0900 Subject: [PATCH] server: render .json urls --- server/build.js | 4 ++-- server/index.js | 7 +++++-- server/render.js | 5 ++++- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/server/build.js b/server/build.js index 62f63064..04955e2b 100644 --- a/server/build.js +++ b/server/build.js @@ -13,7 +13,7 @@ import moduleAlias from 'babel-plugin-module-alias' const babelRuntimePath = require.resolve('babel-runtime/package') .replace(/[\\\/]package\.json$/, ''); -export function transpile (path, { root = process.cwd() } = {}) { +export function transpile (path) { return new Promise((resolve, reject) => { transformFile(path, { presets: [preset2015, presetReact], @@ -38,7 +38,7 @@ export function transpile (path, { root = process.cwd() } = {}) { }) } -export function bundle (path, { root = process.cwd() } = {}) { +export function bundle (path) { const fs = new MemoryFS() const compiler = webpack({ diff --git a/server/index.js b/server/index.js index b36773a0..34c07fdc 100644 --- a/server/index.js +++ b/server/index.js @@ -66,6 +66,7 @@ export default class Server { } async renderJSON (req, res, path) { + const { root } = this let json try { json = await renderJSON(path, { root }) @@ -75,9 +76,11 @@ export default class Server { } throw err } + + const data = JSON.stringify(json) res.setHeader('Content-Type', 'application/json') - res.setHeader('Content-Length', Buffer.byteLength(json)) - res.end(json) + res.setHeader('Content-Length', Buffer.byteLength(data)) + res.end(data) } async render404 (req, res) { diff --git a/server/render.js b/server/render.js index e0da020d..3d5f3d63 100644 --- a/server/render.js +++ b/server/render.js @@ -39,5 +39,8 @@ export async function render (path, req, res, { root = process.cwd() } = {}) { return '' + renderToStaticMarkup(doc) } -export async function renderJSON (path) { +export async function renderJSON (path, { root = process.cwd() }) { + const bundlePath = resolve(root, '.next', '.next', 'pages', (path || 'index') + '.js') + const component = await fs.readFile(bundlePath, 'utf8') + return { component } }