Guest User

Untitled

a guest
Nov 23rd, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. // Middleware function creates a `ctx.render('homepage', { title, foo })`
  2. // function on the koa context.
  3. const reactRenderware = (root, _opts = {}) => {
  4. const defaultOpts = () => ({ locals: {} })
  5. const { locals: globals, opts } = { ...defaultOpts(), ..._opts }
  6. const { extname } = require('path')
  7. const React = require('react')
  8. const ReactDOMServer = require('react-dom/server')
  9. const Master = require(path.join(root, 'master.jsx'))
  10. return async (ctx, next) => {
  11. ctx.render = (templatePath, locals) => {
  12. const fullpath = path.join(
  13. root,
  14. extname(templatePath) ? templatePath : templatePath + '.jsx'
  15. )
  16. const Template = require(fullpath)
  17. ctx.type = 'html'
  18. const output = new (require('stream')).PassThrough()
  19. output.write('<!doctype html>')
  20. ReactDOMServer.renderToStaticNodeStream(
  21. <Master {...globals} {...locals} ctx={ctx}>
  22. <Template {...locals} ctx={ctx} />
  23. </Master>
  24. ).pipe(output)
  25. ctx.body = output
  26. }
  27. return next()
  28. }
  29. }
  30.  
  31. // views
  32. // - master.jsx
  33. // - homepage.jsx
  34. // src
  35. // - index.js <-- We are here
  36.  
  37. const viewRoot = require('path').join(__dirname, '../views')
  38.  
  39. // Apply middleware
  40. app.use(reactRenderware(viewRoot))
  41.  
  42. // Example route
  43. app.use(async ctx => {
  44. const messages = await db.latestMessages()
  45. await ctx.render('homepage', {
  46. messages
  47. })
  48. })
Add Comment
Please, Sign In to add comment