From ae8e149850017796606d64a5d8ae6321189df62d Mon Sep 17 00:00:00 2001 From: Cole Bemis Date: Fri, 18 May 2018 17:23:23 -0700 Subject: [PATCH] build: Refactor algolia script to reindex data atomically --- bin/sync-algolia.js | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/bin/sync-algolia.js b/bin/sync-algolia.js index 579dee9..59ee1e7 100644 --- a/bin/sync-algolia.js +++ b/bin/sync-algolia.js @@ -18,20 +18,32 @@ function syncAlgolia() { // ALGOLIA_ADMIN_KEY must be added as an environment variable in Travis CI const client = algolia(ALGOLIA_APP_ID, process.env.ALGOLIA_ADMIN_KEY); + // Initialize the target and temporary indexes const index = client.initIndex('icons'); + const indexTmp = client.initIndex('icons_tmp'); + // Copy the settings, synonyms and rules (but not the records) + // of the target index into the temporary index + client.copyIndex(index.indexName, indexTmp.indexName, [ + 'settings', + 'synonyms', + 'rules', + ]); + + // Push data to the temporary index const records = Object.keys(icons).map(name => ({ name, tags: tags[name] || [], })); - index.clearIndex((err, content) => { + indexTmp.addObjects(records, (err, content) => { if (err) throw err; console.log(content); + }); - index.addObjects(records, (err, content) => { - if (err) throw err; - console.log(content); - }); + // Move the temporary index to the target index + client.moveIndex(indexTmp.indexName, index.indexName, (err, content) => { + if (err) throw err; + console.log(content); }); }