forked from algolia/algolia-sitemap
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
83 lines (76 loc) · 2.06 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
const algoliasearch = require('algoliasearch');
const { createSitemapindex, createSitemap } = require('./sitemap');
const { saveSiteMap } = require('./saveFiles');
const CHUNK_SIZE = 50000;
function init({
algoliaConfig,
params,
sitemapLoc,
outputFolder,
hitToParams,
}) {
let batch = [];
const client = algoliasearch(algoliaConfig.appId, algoliaConfig.apiKey);
const indexes = algoliaConfig.indexNames.map(indexName =>
client.initIndex(indexName)
);
let index = indexes.pop();
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;
do {
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();
}
({ hits, cursor } = await index.browseFrom(cursor));
if (!cursor && indexes.length > 0) {
index = indexes.pop();
({ hits, cursor } = await index.browse());
// eslint-disable-next-line no-continue
continue;
}
} while (cursor);
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;