forked from shakacode/react-webpack-rails-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server-express.js
62 lines (54 loc) · 1.71 KB
/
server-express.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/* eslint-disable no-console, func-names, no-var */
var bodyParser = require('body-parser');
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var pug = require('pug');
var sleep = require('sleep');
var config = require('./webpack.client.express.config');
var uuid = require('node-uuid');
var comments = [
{ author: 'Pete Hunt', text: 'Hey there!', id: uuid.v4() },
{ author: 'Justin Gordon', text: 'Aloha from @railsonmaui', id: uuid.v4() },
];
var server = new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true,
stats: {
colors: true,
hash: false,
version: false,
chunks: false,
children: false,
},
});
server.app.use(bodyParser.json(null));
server.app.use(bodyParser.urlencoded({ extended: true }));
server.app.get('/comments.json', (req, res) => {
sleep.sleep(1);
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ comments }));
});
server.app.post('/comments.json', (req, res) => {
const comment = req.body.comment;
comment.id = uuid.v4();
console.log('Processing comment: %j', comment);
console.log('(shhhh...napping 1 seconds)');
sleep.sleep(1);
console.log('Just got done with nap!');
comments.push(comment);
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(comment));
});
server.app.use('/', (req, res) => {
var locals = {
props: JSON.stringify({ comments }),
};
var layout = `${process.cwd()}/index.pug`;
var html = pug.compileFile(layout, { pretty: true })(locals);
res.send(html);
});
server.listen(4000, 'localhost', (err) => {
if (err) console.log(err);
console.log('Listening at localhost:4000...');
});