-
Notifications
You must be signed in to change notification settings - Fork 15
/
index.js
99 lines (91 loc) · 2.42 KB
/
index.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
const algoliasearch = require('algoliasearch');
const { createSitemapindex, createSitemap } = require('./sitemap');
const { saveSiteMap } = require('./saveFiles');
const CHUNK_SIZE = 50000;
function init({
algoliaConfig,
params,
sitemapLoc,
outputFolder,
hitToParams,
}) {
if (!algoliaConfig) {
throw new Error('Missing algoliaConfig');
}
if (
!algoliaConfig.appId ||
!algoliaConfig.apiKey ||
!algoliaConfig.indexName
) {
throw new Error('Missing credentials in algoliaConfig');
}
if (!sitemapLoc) {
throw new Error(
'Missing sitemapLoc (e.g. https://www.example.org/sitemaps)'
);
}
if (typeof hitToParams !== 'function') {
throw new Error('Missing hitToParams function');
}
let batch = [];
const client = algoliasearch(algoliaConfig.appId, algoliaConfig.apiKey);
const index = client.initIndex(algoliaConfig.indexName);
const sitemaps = [];
const handleSitemap = async entries =>
sitemaps.push({
loc: `${sitemapLoc}/${await saveSiteMap({
sitemap: createSitemap(entries),
index: sitemaps.length,
root: outputFolder,
})}`,
lastmod: new Date().toISOString(),
});
const flush = async () => {
const chunks = [];
let chunk = [];
batch.forEach(entry => {
if (chunk.length < CHUNK_SIZE) {
chunk.push(entry);
}
if (chunk.length === CHUNK_SIZE) {
chunks.push(chunk);
chunk = [];
}
});
await Promise.all(chunks.map(handleSitemap));
batch = chunk;
};
const aggregator = async args => {
let { hits, cursor } = args;
batch = batch.concat(
hits.reduce((entries, hit) => {
const entry = hitToParams(hit);
return entry ? entries.concat(entry) : entries;
}, [])
);
while (cursor) {
({ hits, cursor } = await index.browseFrom(cursor));
if (!hits) {
return;
}
batch = batch.concat(
hits.reduce((entries, hit) => {
const entry = hitToParams(hit);
return entry ? entries.concat(entry) : entries;
}, [])
);
if (batch.length > CHUNK_SIZE) {
await flush();
}
}
await handleSitemap(batch);
const sitemapIndex = createSitemapindex(sitemaps);
await saveSiteMap({
sitemap: sitemapIndex,
root: outputFolder,
filename: 'sitemap-index',
});
};
return index.browse(params).then(aggregator);
}
module.exports = init;