/
internals.js
120 lines (104 loc) · 2.7 KB
/
internals.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import fs from "fs"
import pify from "pify"
import minimatch from "minimatch"
export const withoutTrailingSlash = path =>
path === `/` ? path : path.replace(/\/$/, ``)
export const writeFile = pify(fs.writeFile)
export const renameFile = pify(fs.rename)
export function filterQuery(
results,
excludes,
pathPrefix,
resolveSiteUrl = defaultOptions.resolveSiteUrl
) {
const { errors, data } = results
if (errors) {
throw new Error(errors.join(`, `))
}
let { allPages, originalType } = getNodes(data.allSitePage)
// Removing excluded paths
allPages = allPages.filter(
page =>
!excludes.some(excludedRoute =>
minimatch(
withoutTrailingSlash(page.path),
withoutTrailingSlash(excludedRoute)
)
)
)
// Add path prefix
allPages = allPages.map(page => {
page.path = (pathPrefix + page.path).replace(/^\/\//g, `/`)
return page
})
// siteUrl Validation
let siteUrl = resolveSiteUrl(data)
if (!siteUrl || siteUrl.trim().length == 0) {
throw new Error(
`SiteMetaData 'siteUrl' property is required and cannot be left empty. Check out the documentation to see a working example: https://www.gatsbyjs.org/packages/gatsby-plugin-sitemap/#how-to-use`
)
}
// remove trailing slash of siteUrl
siteUrl = withoutTrailingSlash(siteUrl)
return {
allSitePage: {
[originalType]:
originalType === `nodes`
? allPages
: allPages.map(page => {
return { node: page }
}),
},
site: { siteMetadata: { siteUrl } },
}
}
export const defaultOptions = {
query: `
{
site {
siteMetadata {
siteUrl
}
}
allSitePage {
edges {
node {
path
}
}
}
}`,
output: `/sitemap.xml`,
exclude: [
`/dev-404-page`,
`/404`,
`/404.html`,
`/offline-plugin-app-shell-fallback`,
],
createLinkInHead: true,
serialize: ({ site, allSitePage }) => {
const { allPages } = getNodes(allSitePage)
return allPages?.map(page => {
return {
url: `${site.siteMetadata?.siteUrl ?? ``}${page.path}`,
changefreq: `daily`,
priority: 0.7,
}
})
},
resolveSiteUrl: data => data.site.siteMetadata.siteUrl,
}
function getNodes(results) {
if (`nodes` in results) {
return { allPages: results.nodes, originalType: `nodes` }
}
if (`edges` in results) {
return {
allPages: results?.edges?.map(edge => edge.node),
originalType: `edges`,
}
}
throw new Error(
`[gatsby-plugin-sitemap]: Plugin is unsure how to handle the results of your query, you'll need to write custom page filter and serilizer in your gatsby conig`
)
}