Algolia index manager

Algolia index manager

HTML

<script src="https://cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/algoliasearch/3/algoliasearch.jquery.min.js"></script>

JavaScript

var AlgoliaIndexMgr = (function(indexName) {
  var APPID = "Q5XXXXXXBP";
  var ADMIN_API_KEY = "1exxxxxxxxxxxxxxxxxxxxxxxxxxxx2d";

  var client = algoliasearch(APPID, ADMIN_API_KEY, {
    protocol: 'https:'
  });
  var index = client.initIndex(indexName);

  var getIndexedAttributes = function() {
    return index
      .getSettings()
      .then(function(content) {
        return content.attributesToIndex;
      });
  };

  var updateRecords = function(newRecordsDataArray, doWait) {
    // Check that objectID is present in each passed object and collect objectIDs
    var objIds = [];
    var badRecords = [];
    
    newRecordsDataArray.forEach(function(o, i) {
      if (!o.objectID) {
      	badRecords.push(i);
      } else {
      	objIds.push(o.objectID);
      }
    });
    
    if (badRecords.length > 0) {
    	var msg = "updateRecords error: objectID not specified in objects with indexes: " + badRecords.join();
      console.error(msg);
      return new Promise(function(resolve, reject) {
        reject(new Error(msg));
      });
    }

    // Check the object exists and preform update
    return index.getObjects(objIds)
      .then(function(content) {
        // Perform update
        if (!doWait) {
        	// Async mode
        	return index.partialUpdateObjects(newRecordsDataArray);
        }
        // Sync mode
        return index.partialUpdateObjects(newRecordsDataArray)
        	.then(_waitBackendTask);
      })
      .catch(function(err) {
        console.error("updateRecords error: " + err);
      });
  };

  var addRecords = function(newRecordsDataArray, doWait) {
  	if (!doWait) {
    	return index.addObjects(newRecordsDataArray);
    }
    
    // Wait for completion of the batch operation (sync mode)
    return index.addObjects(newRecordsDataArray)
      .then(_waitBackendTask);
  };

  var deleteRecords = function(objectIDArray) {
    return index.deleteObjects(objectIDArray);
  };

  var getRecords = function(objectIDArray) {
    return...