-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
86 lines (72 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const compression = require('compression');
const helpers = require('./helpers');
const server = express();
const DIST_PATH = path.resolve('dist');
server.use(bodyParser.urlencoded({ extended: true }));
server.use(bodyParser.json());
server.use(compression());
server.use(helpers.setSecurityHeaders);
server.use(express.static(DIST_PATH, { extensions: ['html'] }));
server.use(express.static(path.resolve('public')));
// static routes
server.get('/blog', (req, res) => {
const { tag = '', page = 1 } = req.query;
const filename = `blog-${tag || 'all'}-${page}.html`;
res.sendFile(filename, { root: DIST_PATH });
});
server.get('/blog/:name', (req, res) => {
res.sendFile(`${req.params.name}.html`, { root: DIST_PATH });
});
// json routes
server.get('/json/blog', (req, res) => {
const { tag = '', page = 1 } = req.query;
const { posts, total } = helpers.getPosts(tag, +page);
res.status(200).send({
success: true,
result: {
posts,
tag,
total,
page: +page,
},
});
});
server.get('/json/blog/:name', (req, res) => {
const post = helpers.getPost(req.params.name);
res.status(200).send({
success: true,
result: post,
});
});
server.get('/json/talk', (req, res) => {
const talk = helpers.getRandomTalk();
res.header('Cache-Control', 'no-cache');
return res.status(200).send({
success: true,
result: talk,
});
});
if (process.env.NODE_ENV !== 'production') {
/* eslint-disable global-require, import/no-extraneous-dependencies */
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const config = require('./webpack.config')(null, { mode: 'development' });
const compiler = webpack(config);
server.use(webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath,
stats: 'minimal',
}));
server.use(webpackHotMiddleware(compiler));
}
server.listen(process.env.PORT || 4000, (err) => {
if (err) {
throw err;
} else {
/* eslint-disable no-console */
console.log(`server listening on port ${process.env.PORT || 4000}`);
}
});