Skip to content

Commit c34fa1c

Browse files
author
Melissa Garcia
committed
add redirections script
1 parent 40bbf14 commit c34fa1c

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

buildRedirections.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
const path = require('path');
2+
const fs = require('node:fs');
3+
const { pathPrefix } = require('./gatsby-config.js');
4+
const { globSync }= require('glob');
5+
6+
try {
7+
if(!pathPrefix) {
8+
throw new TypeError("pathPrefix not found");
9+
}
10+
11+
let results = globSync(__dirname + '/src/pages/**/*.md');
12+
let data = [];
13+
14+
results.forEach(result => {
15+
const nonNormalizedMdFilePath = result.replace(__dirname + '/src/pages', pathPrefix);
16+
const mdFilePath = path.resolve(nonNormalizedMdFilePath);
17+
18+
// Fixes paths that don't end in a trailing slash but should.
19+
// index.md has a directory-level URL that needs a trailing slash
20+
if(mdFilePath.includes('index.md')) {
21+
const source = mdFilePath.replace('/index.md', '');
22+
data.push({
23+
"Source" : source,
24+
"Destination" : source + '/'
25+
});
26+
}
27+
28+
// Fixes paths that end in a trailing slash but shouldn't.
29+
// skip any index.md or config.md as they don't need redirect
30+
if(!mdFilePath.includes('index.md') && !mdFilePath.includes('config.md')) {
31+
const source = mdFilePath.replace('.md', '/');
32+
data.push({
33+
"Source" : source,
34+
"Destination" : source.replace(/\/$/, "")
35+
});
36+
}
37+
});
38+
39+
let redirectionsData =
40+
{
41+
"total" : data.length,
42+
"offset": 0,
43+
"limit": data.length,
44+
"data" : data,
45+
":type": "sheet"
46+
};
47+
48+
let redirectionsFilePath = path.resolve(__dirname + '/src/pages/redirects.json');
49+
fs.writeFileSync(redirectionsFilePath, JSON.stringify(redirectionsData));
50+
51+
} catch (err) {
52+
console.error(err);
53+
}

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@
3232
"clean": "gatsby clean",
3333
"test:links": "remark src/pages --quiet --frail",
3434
"lint": "docker run --rm -e RUN_LOCAL=true --env-file '.github/super-linter.env' -v \"$PWD\":/tmp/lint github/super-linter:slim-v4.10.1",
35-
"buildNavigation": "node buildNavigation.js"
35+
"buildNavigation": "node buildNavigation.js",
36+
"buildRedirections": "node buildRedirections.js"
3637
},
3738
"remarkConfig": {
3839
"plugins": [

0 commit comments

Comments
 (0)