-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
69 lines (60 loc) · 2.23 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
require('babel-register');
if (process.env.NODE_ENV === 'development') {
require('dotenv').config(); //eslint-disable-line
}
const compression = require('compression');
const express = require('express');
const hbs = require('express-handlebars');
const helmet = require('helmet');
const path = require('path');
const serveStatic = require('serve-static');
const favicon = require('serve-favicon');
const firebase = require('firebase');
const firebaseConfig = require('./firebase-config');
// Server Side React
const { match, RouterContext } = require('react-router');
const ReactDOMServer = require('react-dom/server');
const React = require('react');
const Helmet = require('react-helmet');
const ClientApp = require('./app/js/components/App.jsx').default;
const routes = ClientApp.routes;
// Controllers
const EventController = require('./app/js/server/controllers/events-controller');
const app = express();
if (Object.keys(firebaseConfig).some(key => !firebaseConfig[key])) {
console.error('Environment Variable missing for firebase configuration');
} else {
firebase.initializeApp(firebaseConfig);
app.eventRef = firebase.database().ref();
}
// event api endpoints
new EventController(app); // eslint-disable-line
app.use(helmet());
app.use(compression());
app.engine('hbs', hbs({ defaultLayout: 'main', extname: '.hbs' }));
app.set('view engine', 'hbs');
app.use('/static', serveStatic(path.join(__dirname, '/static')));
app.use(favicon(path.join(__dirname, '/static/style/img/favicon.ico')));
app.use((req, res) => {
match({ routes: routes(), location: req.url }, (error, redirectLocation, renderProps) => {
if (error) {
res.status(500).send(error.message);
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search);
} else if (renderProps) {
const DOM = ReactDOMServer.renderToString(
React.createElement(RouterContext, renderProps)
);
const head = Helmet.rewind();
res.render('index', { react: DOM, title: head.title, meta: head.meta });
} else {
res.render('404');
}
});
});
app.listen(process.env.PORT || 7001, (err) => {
if (err) {
console.log(err);
}
console.log(`Express App listening @ port ${process.env.PORT || 7001}`);
});