提交 0e96a299 编写于 作者: J Jason Park

Pass algorithm data to client along with index.html

上级 2fd5a69a
const proxy = require('http-proxy-middleware');
const {
__DEV__,
proxyPort,
backendBuildPath,
apiEndpoint,
} = require('../environment');
if (__DEV__) {
const webpack = require('webpack');
const webpackConfig = require('../webpack.backend.config.js');
const compiler = webpack(webpackConfig);
let backend = null;
let lastHash = null;
let httpServer = null;
compiler.watch({
watchOptions: {
ignored: /public/,
......@@ -24,30 +19,24 @@ if (__DEV__) {
lastHash = null;
compiler.purgeInputFileSystem();
console.error(err);
}
if (stats.hash !== lastHash) {
} else if (stats.hash !== lastHash) {
lastHash = stats.hash;
console.info(stats.toString({
cached: false,
colors: true,
}));
try {
if (httpServer) httpServer.close();
delete require.cache[require.resolve(backendBuildPath)];
const app = require(backendBuildPath).default;
httpServer = app.listen(proxyPort);
} catch (e) {
console.error(e);
}
delete require.cache[require.resolve(backendBuildPath)];
backend = require(backendBuildPath).default;
}
});
module.exports = proxy({
target: `http://localhost:${proxyPort}/`,
pathRewrite: { ['^' + apiEndpoint]: '' },
ws: true,
});
const backendWrapper = (req, res, next) => backend(req, res, next);
backendWrapper.getHierarchy = () => backend.hierarchy;
module.exports = backendWrapper;
} else {
module.exports = require(backendBuildPath).default;
const backend = require(backendBuildPath).default;
const backendWrapper = (req, res, next) => backend(req, res, next);
backendWrapper.getHierarchy = () => backend.hierarchy;
module.exports = backendWrapper;
}
const express = require('express');
const history = require('connect-history-api-fallback');
const path = require('path');
const fs = require('fs');
const url = require('url');
......@@ -12,7 +11,6 @@ const {
} = require('../environment');
const app = express();
app.use(history());
if (__DEV__) {
const webpack = require('webpack');
......@@ -26,27 +24,49 @@ if (__DEV__) {
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 {
const { hierarchy } = require('./backend'); // TODO: Hmm...
app.get('/index.html', (req, res, next) => {
const [, categoryKey, algorithmKey] = url.parse(req.originalUrl).pathname.split('/');
let { title, description } = packageJson;
const algorithm = hierarchy.find(categoryKey, algorithmKey);
if (algorithm) {
title = [algorithm.categoryName, algorithm.algorithmName].join(' - ');
description = algorithm.description;
}
app.use(express.static(frontendBuildPath));
app.use((req, res, next) => {
const filePath = path.resolve(frontendBuildPath, 'index.html');
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) next(err);
const result = data.replace(/\$TITLE/g, title).replace(/\$DESCRIPTION/g, description);
res.send(result);
if (err) return next(err);
res.indexFile = data;
next();
});
});
app.use(express.static(frontendBuildPath));
}
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;
const algorithm = hierarchy.find(categoryKey, algorithmKey);
if (algorithm) {
title = [algorithm.categoryName, algorithm.algorithmName].join(' - ');
description = algorithm.description;
}
const indexFile = res.indexFile
.replace(/\$TITLE/g, title)
.replace(/\$DESCRIPTION/g, description)
.replace(/\$ALGORITHM/g, algorithm ? JSON.stringify(algorithm).replace(/</g, '\\u003c') : 'undefined');
res.send(indexFile);
});
module.exports = app;
......@@ -6,7 +6,6 @@ const {
HTTP_PORT = '8080',
HTTPS_PORT = '8443',
PROXY_PORT = '3000',
GITHUB_CLIENT_ID,
GITHUB_CLIENT_SECRET,
......@@ -26,7 +25,6 @@ const __DEV__ = !__PROD__;
const httpPort = parseInt(HTTP_PORT);
const httpsPort = parseInt(HTTPS_PORT);
const proxyPort = parseInt(PROXY_PORT);
const githubClientId = GITHUB_CLIENT_ID;
const githubClientSecret = GITHUB_CLIENT_SECRET;
......@@ -54,7 +52,6 @@ module.exports = {
__DEV__,
httpPort,
httpsPort,
proxyPort,
githubClientId,
githubClientSecret,
githubWebhookSecret,
......
此差异已折叠。
......@@ -4,7 +4,6 @@ import { connect } from 'react-redux';
import Promise from 'bluebird';
import { Helmet } from 'react-helmet';
import AutosizeInput from 'react-input-autosize';
import removeMarkdown from 'remove-markdown';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import faPlus from '@fortawesome/fontawesome-free-solid/faPlus';
import {
......@@ -142,7 +141,10 @@ class App extends BaseComponent {
loadAlgorithm({ categoryKey, algorithmKey, gistId }) {
const { ext } = this.props.env;
const fetch = () => {
if (categoryKey && algorithmKey) {
if (window.__PRELOADED_ALGORITHM__) {
this.props.setAlgorithm(window.__PRELOADED_ALGORITHM__);
delete window.__PRELOADED_ALGORITHM__;
} else if (categoryKey && algorithmKey) {
return AlgorithmApi.getAlgorithm(categoryKey, algorithmKey)
.then(({ algorithm }) => this.props.setAlgorithm(algorithm));
} else if (gistId === 'new') {
......@@ -153,30 +155,32 @@ class App extends BaseComponent {
title: 'Untitled',
files: [CONTRIBUTING_MD, language.skeleton],
});
return Promise.resolve();
} else if (gistId) {
return GitHubApi.getGist(gistId, { timestamp: Date.now() })
.then(refineGist)
.then(this.props.setScratchPaper);
} else {
this.props.setHome();
return Promise.resolve();
}
return Promise.resolve();
};
fetch()
.then(() => this.selectDefaultTab())
.catch(error => {
this.handleError(error);
this.props.history.push('/');
})
.finally(() => {
const { files } = this.props.current;
let editorTabIndex = files.findIndex(file => extension(file.name) === ext);
if (!~editorTabIndex) editorTabIndex = files.findIndex(file => exts.includes(extension(file.name)));
if (!~editorTabIndex) editorTabIndex = Math.min(0, files.length - 1);
this.handleChangeEditorTabIndex(editorTabIndex);
});
}
selectDefaultTab() {
const { ext } = this.props.env;
const { files } = this.props.current;
let editorTabIndex = files.findIndex(file => extension(file.name) === ext);
if (!~editorTabIndex) editorTabIndex = files.findIndex(file => exts.includes(extension(file.name)));
if (!~editorTabIndex) editorTabIndex = Math.min(0, files.length - 1);
this.handleChangeEditorTabIndex(editorTabIndex);
}
handleChangeWorkspaceWeights(workspaceWeights) {
this.setState({ workspaceWeights });
this.codeEditorRef.current.getWrappedInstance().handleResize();
......
......@@ -27,5 +27,8 @@
</head>
<body>
<div id="root" style="height: 100%"></div>
<script>
window.__PRELOADED_ALGORITHM__ = $ALGORITHM;
</script>
</body>
</html>
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册