From e52e6c6d5af1edb97fb1af2f50a3037cf4a1115a Mon Sep 17 00:00:00 2001 From: Richie Date: Sat, 14 Jul 2018 04:06:26 +0900 Subject: [PATCH] =?UTF-8?q?Dynamically=20append=20path=20alias=20(aaa/bbb.?= =?UTF-8?q?html=20=3D=20aaa/bbb=20=3D=20aaa/bbb/)=20int=E2=80=A6=20(#783)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Dynamically append path alias (aaa/bbb.html = aaa/bbb = aaa/bbb/) into redirects during gatsby onCreateNode callback API to avoid 404 * Consider more cases: (1) markdown without redirects (2) duplicated permalink for /docs/pure-render-mixin.html, rename the unused one * Test permalink with ending `.html` rather then containing them --- content/docs/reference-pure-render-mixin.md | 2 +- gatsby/onCreateNode.js | 19 +++++++++++++++++-- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/content/docs/reference-pure-render-mixin.md b/content/docs/reference-pure-render-mixin.md index 6da08e31..1b5b56b9 100644 --- a/content/docs/reference-pure-render-mixin.md +++ b/content/docs/reference-pure-render-mixin.md @@ -3,7 +3,7 @@ id: pure-render-mixin title: PureRenderMixin layout: docs category: Reference -permalink: docs/pure-render-mixin.html +permalink: docs/pure-render-mixin-old.html --- > Note diff --git a/gatsby/onCreateNode.js b/gatsby/onCreateNode.js index bc79b7a4..e8731eff 100644 --- a/gatsby/onCreateNode.js +++ b/gatsby/onCreateNode.js @@ -9,6 +9,20 @@ // Parse date information out of blog post filename. const BLOG_POST_FILENAME_REGEX = /([0-9]+)\-([0-9]+)\-([0-9]+)\-(.+)\.md$/; +function buildRedirectString(permalink, redirect_from) { + if (!permalink || !permalink.endsWith('.html')) { + return redirect_from ? JSON.stringify(redirect_from) : ''; + } + + let basePath = permalink.slice(0, -'.html'.length); + let redirects = [basePath, basePath + '/']; + if (Array.isArray(redirect_from)) { + redirects = redirects.concat(redirect_from); + } + + return JSON.stringify(redirects); +} + // Add custom fields to MarkdownRemark nodes. module.exports = exports.onCreateNode = ({node, boundActionCreators, getNode}) => { const {createNodeField} = boundActionCreators; @@ -67,8 +81,9 @@ module.exports = exports.onCreateNode = ({node, boundActionCreators, getNode}) = createNodeField({ node, name: 'redirect', - value: redirect_from ? JSON.stringify(redirect_from) : '', + value: buildRedirectString(permalink, redirect_from), }); + return; } -}; \ No newline at end of file +};