Refactor(server): share logic between server.js & generate.js (#856)

* nits too many comments

* Refactor to blog.getPages

* Refactor to getPost, fileToUrl, urlToFile

* Refactor redirectcomponent generation for docs

* nits & fix typo

* Refactor to blog.getMetadata

* Add test for getMetadata, fileToSUrl and urlToSource

* use includes() and add 'markup' naming for function
This commit is contained in:
Endilie Yacop Sucipto 2018-07-24 13:37:52 +07:00 committed by GitHub
parent bbfb4b09cb
commit afec4bd47c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 249 additions and 214 deletions

View file

@ -9,10 +9,9 @@
function execute(port, options) {
const extractTranslations = require('../write-translations');
const metadataUtils = require('./metadataUtils');
const blog = require('./blog');
const docs = require('./docs');
const env = require('./env.js');
const express = require('express');
const React = require('react');
@ -25,17 +24,13 @@ function execute(port, options) {
const chalk = require('chalk');
const gaze = require('gaze');
const tinylr = require('tiny-lr');
const constants = require('../core/constants');
const translate = require('./translate');
const {renderToStaticMarkupWithDoctype} = require('./renderUtils');
const feed = require('./feed');
const sitemap = require('./sitemap');
const routing = require('./routing');
const CWD = process.cwd();
const join = path.join;
const sep = path.sep;
@ -46,7 +41,6 @@ function execute(port, options) {
delete module.constructor._pathCache[cacheKey];
}
});
/* eslint-enable no-underscore-dangle */
}
// Remove a module and child modules from require cache, so server
@ -112,7 +106,6 @@ function execute(port, options) {
}
function startLiveReload() {
// Start LiveReload server.
process.env.NODE_ENV = 'development';
const server = tinylr();
server.listen(constants.LIVE_RELOAD_PORT, () => {
@ -122,19 +115,10 @@ function execute(port, options) {
);
});
// gaze watches some specified dirs and triggers a callback when they change.
gaze(
[
`../${readMetadata.getDocsPath()}/**/*`, // docs
'**/*', // website
'!node_modules/**/*', // node_modules
],
[`../${readMetadata.getDocsPath()}/**/*`, '**/*', '!node_modules/**/*'],
function() {
// Listen for all kinds of file changes - modified/added/deleted.
this.on('all', () => {
// Notify LiveReload clients that there's a change.
// Typically, LiveReload will only refresh the changed paths,
// so we use / here to force a full-page reload.
server.notifyClients(['/']);
});
}
@ -148,7 +132,6 @@ function execute(port, options) {
const app = express();
// handle all requests for document pages
app.get(routing.docs(siteConfig.baseUrl), (req, res, next) => {
const url = req.path.toString().replace(siteConfig.baseUrl, '');
const metadata =
@ -163,8 +146,7 @@ function execute(port, options) {
const rawContent = metadataUtils.extractMetadata(file).rawContent;
removeModuleAndChildrenFromCache('../core/DocsLayout.js');
const mdToHtml = metadataUtils.mdToHtml(Metadata, siteConfig.baseUrl);
const docComp = docs.getComponent(rawContent, mdToHtml, metadata);
res.send(renderToStaticMarkupWithDoctype(docComp));
res.send(docs.getMarkup(rawContent, mdToHtml, metadata));
});
app.get(routing.sitemap(siteConfig.baseUrl), (req, res) => {
@ -192,97 +174,32 @@ function execute(port, options) {
next();
});
// Handle all requests for blog pages and posts.
app.get(routing.blog(siteConfig.baseUrl), (req, res, next) => {
// Regenerate the blog metadata in case it has changed. Consider improving
// this to regenerate on file save rather than on page request.
reloadMetadataBlog();
// Generate all of the blog pages.
removeModuleAndChildrenFromCache(join('..', 'core', 'BlogPageLayout.js'));
const BlogPageLayout = require(join('..', 'core', 'BlogPageLayout.js'));
const blogPages = {};
// Make blog pages with 10 posts per page.
const perPage = 10;
for (
let page = 0;
page < Math.ceil(MetadataBlog.length / perPage);
page++
) {
const language = 'en';
const metadata = {page, perPage};
const blogPageComp = (
<BlogPageLayout
metadata={metadata}
language={language}
config={siteConfig}
/>
);
const str = renderToStaticMarkupWithDoctype(blogPageComp);
const blogPages = blog.getPagesMarkup(MetadataBlog.length, siteConfig);
const urlPath = req.path.toString().split('blog/')[1];
const pagePath = `${page > 0 ? `page${page + 1}` : ''}/index.html`;
blogPages[pagePath] = str;
}
const parts = req.path.toString().split('blog/');
// send corresponding blog page if appropriate
if (parts[1] === 'index.html') {
if (urlPath === 'index.html') {
res.send(blogPages['/index.html']);
} else if (parts[1].endsWith('/index.html') && blogPages[parts[1]]) {
res.send(blogPages[parts[1]]);
} else if (parts[1].match(/page([0-9]+)/)) {
if (parts[1].endsWith('/')) {
res.send(blogPages[`${parts[1]}index.html`]);
} else {
res.send(blogPages[`${parts[1]}/index.html`]);
}
} else if (urlPath.endsWith('/index.html') && blogPages[urlPath]) {
res.send(blogPages[urlPath]);
} else if (urlPath.match(/page([0-9]+)/)) {
res.send(blogPages[`${urlPath.replace(/\/$/, '')}/index.html`]);
} else {
// send corresponding blog post. Ex: request to "blog/test/index.html" or
// "blog/test.html" will return html rendered version of "blog/test.md"
let file = parts[1];
if (file.endsWith('/index.html')) {
file = file.replace(/\/index.html$/, '.md');
} else {
file = file.replace(/\.html$/, '.md');
}
file = file.replace(new RegExp('/', 'g'), '-');
file = join(CWD, 'blog', file);
if (!fs.existsSync(file)) {
const file = join(CWD, 'blog', blog.urlToSource(urlPath));
removeModuleAndChildrenFromCache(join('..', 'core', 'BlogPostLayout.js'));
const blogPost = blog.getPostMarkup(file, siteConfig);
if (!blogPost) {
next();
return;
}
const result = metadataUtils.extractMetadata(
fs.readFileSync(file, {encoding: 'utf8'})
);
let rawContent = result.rawContent;
rawContent = rawContent.replace(
/\]\(assets\//g,
`](${siteConfig.baseUrl}blog/assets/`
);
const metadata = Object.assign(
{path: req.path.toString().split('blog/')[1], content: rawContent},
result.metadata
);
metadata.id = metadata.title;
const language = 'en';
removeModuleAndChildrenFromCache(join('..', 'core', 'BlogPostLayout.js'));
const BlogPostLayout = require(join('..', 'core', 'BlogPostLayout.js'));
const blogPostComp = (
<BlogPostLayout
metadata={metadata}
language={language}
config={siteConfig}>
{rawContent}
</BlogPostLayout>
);
res.send(renderToStaticMarkupWithDoctype(blogPostComp));
res.send(blogPost);
}
});
// handle all other main pages
app.get(routing.page(siteConfig.baseUrl), (req, res, next) => {
// Look for user-provided HTML file first.
let htmlFile = req.path.toString().replace(siteConfig.baseUrl, '');
@ -390,7 +307,6 @@ function execute(port, options) {
}
});
// generate the main.css file by concatenating user provided css to the end
app.get(/main\.css$/, (req, res) => {
const mainCssPath = join(
__dirname,
@ -473,7 +389,7 @@ function execute(port, options) {
});
// handle special cleanUrl case like '/blog/1.2.3' & '/blog.robots.hai'
// where we should try to serve 'blog/1.2.3.html' & '/blog.robots.hai.html'
// where we should try to serve '/blog/1.2.3.html' & '/blog.robots.hai.html'
app.get(routing.dotfiles(), (req, res, next) => {
if (!siteConfig.cleanUrl) {
next();