JSFiddle - React, Tailwind, and code Playground

by Patrick Thurmond

JavaScript

require('dotenv').config();
var SiteSearchClient = require("@elastic/site-search-node");

// These values come from the Swiftype Dashboard
var apiKey = process.env.API_KEY;
var engineSlug = process.env.ENGINE_SLUG;

if (apiKey == null) {
  console.log('Config not loaded');
  return;
}

var client = new SiteSearchClient({
  apiKey: apiKey
});

var query = 'brush';

class SearchBar {
  swiftypeApiKey = null;
  swiftypeEngineSlug = null;
  resultPageLimit = 10;
  client = null;
  searchResults = null;
  storageKey = null;
  _cache = {};

  constructor(apiKey, engineSlug, pageLimit) {
    this.swiftypeApiKey = apiKey;
    this.swiftypeEngineSlug = engineSlug;
    this.resultPageLimit = pageLimit;
    this.storageKey = 'searchResults';
    this.initSwiftypeClient();
  }

  initSwiftypeClient() {
    if (this.swiftypeApiKey != null && this.swiftypeEngineSlug != null) {
      this.client = new SiteSearchClient({ apiKey: this.swiftypeApiKey });
    }
  }

  // Swifttype search functions
  async search(query, callback) {
    if (query != null && query !== "") {
      const result = await this.searchCall(query);

      result.then((res) => {
        this.setSearchResults(res);
        console.log('The awaited results');
        console.log(this.getSearchResults());

        return this.getSearchResults();
      }).then(callback);
    }
  }

  async searchCall(query) {
    return new Promise((resolve, reject) => {
      this.client.search({
          engine: this.swiftypeEngineSlug,
          q: query,
        },
        function (err, res) {
          if (err) {
            reject(err);
          }

          resolve(res);
        }
      );
    });
  }

  /**
   * Retrieves the processed search results.
   */
  getSearchResults() {
    console.log('Getting results.');
    console.log(this.searchResults);

    if (this.searchResults == null) {
      if (typeof localStorage !== 'undefined' && localStorage.getItem(this.storageKey) != null) {
        this.searchResults =...