-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
52 lines (43 loc) · 1.69 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
const axios = require('axios')
const algoliasearch = require('algoliasearch')
const StoryblokClient = require('storyblok-js-client')
class StoryblokAlgoliaIndexer {
constructor({
algoliaAppId,
algoliaApiAdminToken,
algoliaIndexName,
storyblokContentDeliveryApiToken,
options
}) {
const algolia = algoliasearch(algoliaAppId, algoliaApiAdminToken)
const storyblok = new StoryblokClient({ accessToken: storyblokContentDeliveryApiToken })
const storyblokOptions = options || {
starts_with: '',
per_page: 100,
page: 1,
version: 'draft'
}
storyblok.get(`cdn/stories/`, storyblokOptions).then(async res => {
const total = res.headers.total
const maxPage = Math.ceil(total / storyblokOptions.per_page)
let contentRequests = []
for (let page = 1; page <= maxPage; page++) {
contentRequests.push(storyblok.get(`cdn/stories/`, { ...storyblokOptions, page }))
}
const index = algolia.initIndex(algoliaIndexName)
axios.all(contentRequests).then(axios.spread(async (...responses) => {
let records = []
responses.forEach((response) => {
let data = response.data
records = records.concat(data.stories[0].content.body)
})
records.forEach(record => {
record.objectID = record._uid
})
await index.saveObjects(records, { autoGenerateObjectIDIfNotExist: false }).wait().catch(e => { console.log(e) })
console.log('Index stored with ' + records.length + ' Entries.')
})).catch(e => { console.log(e) })
}).catch(e => { console.log(e) })
}
}
module.exports = StoryblokAlgoliaIndexer