-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
70 lines (60 loc) · 2.21 KB
/
server.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
63
64
65
66
67
68
69
70
require('dotenv').config({ silent: true });
const express = require('express');
const app = express();
const path = require('path');
const fs = require('fs');
const http = require('http');
const moment = require('moment-timezone');
moment.tz.setDefault('UTC');
const serialize = require('serialize-javascript');
app.use('/public', express.static(path.join(__dirname, 'public')));
let events = [
{ description: 'Random event 1', date: moment('2017-02-06', 'YYYY-MM-DD') },
{ description: 'Random event 2', date: moment('2017-02-15', 'YYYY-MM-DD') },
{ description: 'Random event 3', date: moment('2017-03-14', 'YYYY-MM-DD') }
];
let renderer;
if (process.env.NODE_ENV === 'production') {
let bundle = fs.readFileSync('./dist/node.bundle.js', 'utf8');
renderer = require('vue-server-renderer').createBundleRenderer(bundle);
app.use('/dist', express.static(path.join(__dirname, 'dist')));
}
app.get('/', (req, res) => {
let template = fs.readFileSync(path.resolve('./index.html'), 'utf-8');
let contentMarker = '<!--APP-->';
if (renderer) {
renderer.renderToString({ events }, (err, html) => {
if (err) {
console.log(err);
} else {
res.send(template.replace(contentMarker, `<script>var __INITIAL_STATE__ = ${ serialize(events) }</script>\n${html}`));
}
});
} else {
res.send('<p>Awaiting compilation..</p><script src="/reload/reload.js"></script>');
}
});
app.use(require('body-parser').json());
app.post('/add_event', (req, res) => {
events.push(req.body);
res.sendStatus(200);
});
const server = http.createServer(app);
if (process.env.NODE_ENV === 'development') {
const reload = require('reload');
const reloadServer = reload(server, app);
require('./webpack-dev-middleware').init(app);
require('./webpack-server-compiler').init(function(bundle) {
let needsReload = (renderer === undefined);
renderer = require('vue-server-renderer').createBundleRenderer(bundle);
if (needsReload) {
reloadServer.reload();
}
});
}
server.listen(process.env.PORT, function () {
console.log(`Example app listening on port ${process.env.PORT}!`);
if (process.env.NODE_ENV === 'development') {
require("open")(`http://localhost:${process.env.PORT}`);
}
});