forked from algorithm-visualizer/algorithm-visualizer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfrontend.js
More file actions
78 lines (71 loc) · 2.26 KB
/
frontend.js
File metadata and controls
78 lines (71 loc) · 2.26 KB
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
const express = require('express');
const path = require('path');
const fs = require('fs');
const url = require('url');
const packageJson = require('../package');
const {
__DEV__,
frontendSrcPath,
frontendBuildPath,
} = require('../environment');
const app = express();
if (__DEV__) {
const webpack = require('webpack');
const webpackDev = require('webpack-dev-middleware');
const webpackHot = require('webpack-hot-middleware');
const webpackConfig = require('../webpack.frontend.config.js');
const compiler = webpack(webpackConfig);
app.use(express.static(path.resolve(frontendSrcPath, 'static')));
app.use(webpackDev(compiler, {
stats: {
cached: false,
colors: true,
},
serverSideRender: true,
index: false,
}));
app.use(webpackHot(compiler));
app.use((req, res, next) => {
const { fs } = res.locals;
const outputPath = res.locals.webpackStats.toJson().outputPath;
const filePath = path.resolve(outputPath, 'index.html');
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) return next(err);
res.indexFile = data;
next();
});
});
} else {
app.use(express.static(frontendBuildPath, { index: false }));
app.use((req, res, next) => {
const filePath = path.resolve(frontendBuildPath, 'index.html');
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) return next(err);
res.indexFile = data;
next();
});
});
}
app.use((req, res) => {
const backend = require('./backend');
const hierarchy = backend.getHierarchy();
const [, categoryKey, algorithmKey] = url.parse(req.originalUrl).pathname.split('/');
let { title, description } = packageJson;
let algorithm = undefined;
if (categoryKey && categoryKey !== 'scratch-paper') {
algorithm = hierarchy.find(categoryKey, algorithmKey) || null;
if (algorithm) {
title = [algorithm.categoryName, algorithm.algorithmName].join(' - ');
description = algorithm.description;
} else {
res.status(404);
}
}
const indexFile = res.indexFile
.replace(/\$TITLE/g, title)
.replace(/\$DESCRIPTION/g, description)
.replace(/\$ALGORITHM/g, algorithm === undefined ? 'undefined' :
JSON.stringify(algorithm).replace(/</g, '\\u003c'));
res.send(indexFile);
});
module.exports = app;