sync-algolia.js 1.95 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
import algolia from 'algoliasearch';
import icons from '../dist/icons.json';
import tags from '../src/tags.json';

const ALGOLIA_APP_ID = '5EEOG744D0';

if (
  process.env.TRAVIS_PULL_REQUEST === 'false' &&
  process.env.TRAVIS_BRANCH === 'master'
) {
  syncAlgolia();
12
} else {
Cole Bemis's avatar
Cole Bemis committed
13
  console.log('Skipped Algolia sync.');
14 15 16
}

function syncAlgolia() {
17
  // ALGOLIA_ADMIN_KEY must be added as an environment variable in Travis CI
18 19
  const client = algolia(ALGOLIA_APP_ID, process.env.ALGOLIA_ADMIN_KEY);

20
  console.log('Initializing target and temporary indexes...');
21
  const index = client.initIndex('icons');
22
  const indexTmp = client.initIndex('icons_tmp');
23

24 25 26 27 28 29 30 31 32
  console.log(
    "Copying target index's settings, synonyms and rules into temporary index...",
  );
  scopedCopyIndex(client, index.indexName, indexTmp.indexName)
    .then(() => {
      const objects = Object.keys(icons).map(name => ({
        name,
        tags: tags[name] || [],
      }));
33

34 35 36 37 38 39 40 41
      console.log('Adding objects to the temporary index...');
      return addObjects(indexTmp, objects);
    })
    .then(() => {
      console.log('Moving temporary index to target index...');
      return moveIndex(client, indexTmp.indexName, index.indexName);
    });
}
42

43 44 45 46 47 48 49 50 51 52 53
function scopedCopyIndex(
  client,
  indexNameSrc,
  indexNameDest,
  scope = ['settings', 'synonyms', 'rules'],
) {
  return new Promise((resolve, reject) => {
    client.copyIndex(indexNameSrc, indexNameDest, scope, (error, contents) => {
      if (error) reject(error);
      resolve(contents);
    });
54
  });
55 56 57 58 59 60 61 62 63 64
}

function addObjects(index, objects) {
  return new Promise((resolve, reject) => {
    index.addObjects(objects, (error, contents) => {
      if (error) reject(error);
      resolve(contents);
    });
  });
}
65

66 67 68 69 70 71
function moveIndex(client, indexNameSrc, indexNameDest) {
  return new Promise((resolve, reject) => {
    client.moveIndex(indexNameSrc, indexNameDest, (error, contents) => {
      if (error) reject(error);
      resolve(contents);
    });
72 73
  });
}