Files
buuh/examples/server-rendering/server.js
T

46 lines
1.4 KiB
JavaScript
Raw Normal View History

2016-05-21 21:59:03 +09:00
const serverRouter = require('server-router')
2016-05-23 23:39:22 +09:00
const hyperstream = require('hyperstream')
const browserify = require('browserify')
const bankai = require('bankai')
2016-05-21 21:59:03 +09:00
const http = require('http')
const PORT = 8080
const client = require('./client')
2016-05-23 14:40:52 +09:00
// If an incoming request accepts "text/html", render the
// appropriate HTML. Else use the API server
const apiRouter = createRouter()
const server = http.createServer(function (req, res) {
if (/text\/html/.test(req.headers.accept)) handleHtml(req, res)
else apiRouter(req, res)
})
server.listen(PORT, () => process.stdout.write(`listening on port ${PORT}\n`))
2016-05-21 21:59:03 +09:00
2016-05-23 14:40:52 +09:00
// create a new router
// null -> fn
2016-05-21 21:59:03 +09:00
function createRouter () {
2016-05-23 14:40:52 +09:00
const apiRouter = serverRouter('/404')
2016-05-23 23:39:22 +09:00
apiRouter.on('/404', (req, res) => res.end('404 not found'))
apiRouter.on('/', (req, res) => res.end('nothing to be found here'))
const js = bankai.js(browserify, require.resolve('./client.js'))
apiRouter.on('/bundle.js', (req, res) => js(req, res).pipe(res))
2016-05-23 14:40:52 +09:00
return apiRouter
}
2016-05-21 21:59:03 +09:00
2016-05-23 14:40:52 +09:00
// render the client to string
// based on the requested url
// (obj, obj) -> null
2016-05-23 23:39:22 +09:00
const createIndex = bankai.html({ favicon: false, css: false })
2016-05-23 14:40:52 +09:00
function handleHtml (req, res) {
res.setHeader('Content-Type', 'text/html; charset=utf-8')
2016-05-23 23:39:22 +09:00
const state = { message: { server: 'hello server!' } }
const inner = client.toString(req.url, state)
const hs = hyperstream({ 'body': { _appendHtml: inner } })
createIndex(req, res).pipe(hs).pipe(res)
2016-05-21 21:59:03 +09:00
}