Permalink
Browse files

Load DB on each request to test service worker

  • Loading branch information...
vfeskov committed Dec 29, 2017
1 parent d2f1473 commit 12779367750312ea8b36410c0882f3d548dfdcd7
File renamed without changes.
@@ -20,7 +20,6 @@
"babel-loader": "^7.1.2",
"babel-preset-react-app": "^3.1.0",
"concurrently": "^3.5.1",
"json-loader": "^0.5.7",
"nodemon": "^1.14.0",
"webpack": "^3.10.0",
"webpack-node-externals": "^1.6.0"
@@ -0,0 +1,11 @@
import fs from 'fs'

export default function loadDb () {
return new Promise((r, e) =>
fs.readFile('./db.json', (err, data) => {
if (err) { return e(err) }
const db = JSON.parse(data.toString())
r(db)
})
)
}
@@ -1,9 +1,9 @@
import db from './db.json'
import fs from 'fs'
import finalhandler from 'finalhandler'
import loadDb from './loadDb'

export function api ({ method, url }, res, next) {
export async function api ({ method, url }, res, next) {
if (method !== 'GET' || url !== '/api/posts') { return next() }
const db = await loadDb()
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(db))
}
@@ -1,23 +1,24 @@
import serveStatic from 'serve-static'
import fs from 'fs'
import db from './db.json'
import loadDb from './loadDb'
import { renderToStrings } from '../../client/src/renderToStrings'

export function prerenderClient () {
const layout = fs.readFileSync('./public/layout.html').toString()

return (req, res, next) => {
return async (req, res, next) => {
if (req.method !== 'GET') { return next() }

const app = renderToStrings(db)
const db = await loadDb()
const { html, state } = renderToStrings(db)
const content = layout
.replace(
'<div id="root"></div>',
`<div id="root">${app.html}</div>`
`<div id="root">${html}</div>`
)
.replace(
'</head>',
`<script>window.__INIT_STATE__=${app.state}</script></head>`
`<script>window.__INIT_STATE__=${state}</script></head>`
)
res.writeHead(200, {
'Content-Type': 'text/html',
@@ -20,8 +20,7 @@ const config = {
babelrc: false,
presets: [require.resolve('babel-preset-react-app')]
}
},
{ test: /\.json$/, loader: 'json-loader' }
}
]
},
plugins: [

0 comments on commit 1277936

Please sign in to comment.