forked from audal/gatsby-plugin-yoast-sitemap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-node.js
70 lines (59 loc) · 2.07 KB
/
gatsby-node.js
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
const url = require("url");
const path = require("path");
const axios = require("axios");
const fse = require("fs-extra");
const { extractUrls } = require("./parse-sitemap");
const withoutTrailingSlash = (path) => path === `/` ? path : path.replace(/\/$/, ``);
if (!String.prototype.replaceAll) {
String.prototype.replaceAll = function (find, replace) {
return this.split(find).join(replace);
};
}
exports.createPages = async ({ actions, graphql }, options) => {
const { createRedirect } = actions;
let { baseUrl, gatsbyUrl, auth, publicPath } = options || {};
if (!baseUrl) {
throw new Error("gatsby-plugin-yoast-sitemap: You must define the url for your Wordpress Install. This should not contain /graphql, if using gatsby-source-wordpress.")
}
if (!gatsbyUrl) {
throw new Error("gatsby-plugin-yoast-sitemap: You must define the URL for your Gatsby-hosted site. This may be localhost.")
}
if (!publicPath) publicPath = `./public`
gatsbyUrl = gatsbyUrl.replace("https://", "");
gatsbyUrl = gatsbyUrl.replace("http://", "");
let siteMapIndex = await axios.get(
`https://${withoutTrailingSlash(baseUrl)}/sitemap_index.xml`,
{
auth: auth
}
);
const downloadableXMLNodes = await extractUrls(siteMapIndex.data);
siteMapIndex = siteMapIndex.data.replaceAll(baseUrl, gatsbyUrl);
siteMapIndex = siteMapIndex.replaceAll(
`http://${gatsbyUrl}`,
`https://${gatsbyUrl}`
);
await fse.outputFile(
path.join(publicPath, `sitemap_index.xml`),
siteMapIndex
);
for (const node of downloadableXMLNodes) {
let mapFromNode = await axios.get(node, {
auth: auth,
});
mapFromNode = mapFromNode.data.replaceAll(baseUrl, gatsbyUrl);
mapFromNode = mapFromNode.replaceAll(`https://${gatsbyUrl}`, `https://${gatsbyUrl}`);
const url_parts = url.parse(node);
await fse.outputFile(
path.join(publicPath, url_parts.pathname),
mapFromNode
);
}
createRedirect({
fromPath: `/sitemap.xml`,
toPath: `/sitemap_index.xml`,
isPermanent: false,
redirectInBrowser: true,
force: true,
});
};