I’m trying to create a worker which updates my Algolia index when I send a request to my worker. The algoliasearch
library works in both the browser and Node.js but it seems to be throwing errors inside the Cloudflare Workers environment.
const algoliasearch = require('algoliasearch')
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function fetchPlugins() {
const response = await fetch('https://poggit.pmmp.io/plugins.json')
const json = await response.json()
return json
}
/**
* Create plugins index
*/
function createIndex() {
return new Promise((resolve, reject) => {
const algoliaClient = algoliasearch('XI77W278IB', '91f72a0cbdcb942942d3d6e65364f47f');
const algoliaIndex = algoliaClient.initIndex('prod_POGGIT_SEARCH');
algoliaIndex.setSettings({
searchableAttributes: ['name', 'version', 'keywords', 'tagline'],
customRanking: ['desc(downloads)'],
attributesForFaceting: [],
attributesToSnippet: ['name', 'tagline'],
attributesToHighlight: ['name', 'tagline'],
attributeForDistinct: 'name',
distinct: true,
hitsPerPage: 5
}, (err) => {
if (err) {
reject(err)
} else {
resolve()
}
})
})
}
/**
* Index plugins
*/
function indexPlugins(plugins) {
return new Promise((resolve, reject) => {
const algoliaClient = algoliasearch('ALGOLIA_APP_ID, 'ALGOLIA_API_KEY');
const algoliaIndex = algoliaClient.initIndex('ALGOLIA_INDEX_NAME');
// loop through the plugins and add to a records array
var records = []
for (var i = 0; i < plugins.length; i++) {
var plugin = plugins[i];
records.push(Object.assign({}, plugin))
}
// clear old records from index
algoliaIndex.clearIndex((err) => {
if (err) {
reject(err)
} else {
// then add all the objects in one batch call
algoliaIndex.addObjects(records, (err) => {
if (err) {
reject(err)
} else {
resolve()
}
});
}
})
})
}
/**
* Fetch and log a request
* @param {Request} request
*/
async function handleRequest(request) {
try {
const plugins = await fetchPlugins()
await createIndex()
// await indexPlugins(plugins)
} catch (err) {
console.log(err)
return new Response(JSON.stringify({
success: false,
message: err.message
}), { status: 500 })
}
}