-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
generator.js
166 lines (135 loc) · 4.54 KB
/
generator.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
const path = require("path");
const fs = require("fs");
const Prismic = require("prismic-javascript");
const { SitemapStream, streamToPromise } = require('sitemap');
const paginatorUtil = require('./utils/paginator')
/**
* Generates a sitemap
*
* @param {Object} sitemap The Sitemap Object
* @param {Function} sitemap.linkResolver
* @param {String} sitemap.apiEndpoint
* @param {String} sitemap.accessToken
* @param {String} sitemap.hostname
* @param {Array} sitemap.optionsMapPerDocumentType
* @param {Array} sitemap.documentTypes
* @param {Object} sitemap.sitemapConfig
* @param {Object} sitemap.defaultEntryOption
* @param {Object[]} sitemap.staticPaths
*/
const generator = async (sitemap) => {
const {
linkResolver = null /* doc => { return something } */,
apiEndpoint = '',
accessToken = null,
hostname = '',
optionsMapPerDocumentType = {},
documentTypes = ['*'],
pagination = {
pageSize: 20,
},
fileName = 'sitemap.xml',
publicPath = 'public',
sitemapConfig = {
lastmodDateOnly: true,
},
defaultEntryOption = { changefreq: "monthly", priority: 1, },
staticPaths = [],
/** optional things */
// onBeforeWrite = docs => docs,
// onBeforeStore = stream => stream,
} = sitemap;
if (typeof linkResolver !== 'function') {
throw new Error(
'[Sitemap Generator]: The linkResolver function is undefined, this is needed to build sitemap links'
);
}
if (accessToken !== null && accessToken.length <= 1) {
throw new Error(
'[Sitemap Generator]: The API Access token appears incorrect, please double check as it is short.'
);
}
if (documentTypes === null || documentTypes.length <= 0) {
throw new Error(
'[Sitemap Generator]: The documentTypes option needs a value of 1 or greater in the array'
);
}
/** @todo Add extended options to the Prismic API function, or to pass one from user level */
const api = await Prismic.getApi(apiEndpoint, { 'accessToken': accessToken, });
const paginator = paginatorUtil.init(api, pagination);
let documents = [];
let types = Array.isArray(documentTypes) ? documentTypes : Array.of(documentTypes)
await Promise.all(types.flatMap(type => paginator.paginate(type)))
documents = paginator.results;
const sitemapStream = new SitemapStream({ hostname: hostname, ...sitemapConfig });
documents
.sort((a, b) => a.type < b.type ? -1 : 1) // sort by type
.forEach(doc => {
const options = optionsMapPerDocumentType.hasOwnProperty(doc.type)
? resolveDocumentOption(optionsMapPerDocumentType[doc.type], doc)
: defaultEntryOption;
sitemapStream.write(
Object.assign({ ...options }, { url: linkResolver(doc) })
);
})
/* Handle adding a list of static paths to the sitemap, must be an object */
try {
staticPaths.length >= 1
? staticPaths.forEach(path => storeIfValid(path, sitemapStream))
: null;
} catch (error) {
console.error('[Sitemap Generator]: Unable to save staticPaths to sitemap')
}
sitemapStream.end();
const sitemapData = await streamToPromise(sitemapStream);
let basePath = resolvePublicPath(publicPath)
if (!fs.existsSync(path.join(basePath))) {
fs.mkdirSync(path.join(basePath), { recursive: true });
}
fs.writeFileSync(path.join(basePath, fileName), sitemapData, "utf-8");
return sitemapData;
}
function resolvePublicPath(dir) {
if (dir === 'public') {
dir = path.join(__dirname, dir);
}
return dir;
}
/**
* Resolves if the option is a callback and handles it
* or continues with the object entry.
* @param {Object|Function} option
* @param {Object} document
* @returns Object
*/
function resolveDocumentOption(option, document) {
try {
return typeof option === 'function'
? option(document)
: option;
} catch (error) {
// console.error('[Sitemap Generator]: Failed to handle callback for a document', error);
throw new Error(
`[Sitemap Generator]: Failed to generate a sitemap entry for document {${document.type}}, ${error.message}`
);
}
}
/**
* Adds the static path to the index
*
* @todo Make use of a async callback or handle the object depending on what happens
* @param {Object} option the static path to add
* @param {SitemapStream} stream
* @returns void
*/
function storeIfValid(option, stream) {
if (typeof option === 'function') {
option = option()
}
if (option.url === undefined) {
return;
}
option.lastmod = option.lastmod ? option.lastmod : (new Date).toISOString()
stream.write(option);
}
module.exports = generator;