Building a custom connector

This guide helps you build a custom connector so you can use Search UI with your own API.

A connector is a class that implements the following methods:

  • onSearch
  • onAutocomplete
  • onResultClick
  • onAutocompleteResultClick

Connector Example

Below is an example of a custom connector. Example is given in typescript as the types may be helpful to you.

See Request State, Response State and Search Query Config for more information.


```ts
import type { APIConnector } from "@elastic/search-ui";

class MyAPIConnector implements APIConnector {
  async onSearch(
    state: RequestState,
    queryConfig: QueryConfig
  ): Promise<ResponseState> {
    const { searchTerm, current, filters, sort } = state;
    // perform a request to your API with the request state
    const response = await fetch("https://api.my-host/search", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        searchTerm,
        current,
        filters,
        sort
      })
    });
    // response will need to be in the shape of ResponseState.
    // Alternatively you could transform the response here
    return response.json();
  }

  async onAutocomplete(
    state: RequestState,
    queryConfig: AutocompleteQueryConfig
  ): Promise<AutocompleteResponseState> {
    const response = await fetch(
      "https://api.my-host/autocomplete?query" + state.searchTerm,
      {
        headers: {
          "Content-Type": "application/json"
        }
      }
    );
    // response will need to be in the shape of AutocompleteResponseState.
    // Alternatively you could transform the response here
    return response.json();
  }

  onResultClick(params): void {
    console.log(
      "perform a call to the API to highlight a result has been clicked"
    );
  }

  onAutocompleteResultClick(params): void {
    console.log(
      "perform a call to the API to highlight an autocomplete result has been clicked"
    );
  }
}

Integration

Once you have built your connector, you can simply use it within Search UI.


  const connector = new MyAPIConnector();

  const config = {
    apiConnector: connector,
    searchQuery: { ... },
    autocompleteQuery: { ... }
  };

  const App = () => (
    <SearchProvider config={config}>
      <div className="App">
        <SearchBox />
      </div>
    </SearchProvider>
  );

On this page