Developers

SDK JS-Client

Introduction

The Search JS-Client allows you to call an Inbenta API endpoint quickly and easily with javascript.

Note

All examples shown are set in a Production environment.

Setup

Steps to follow:

  1. Integration

    Include the Inbenta Search JS-Client script somewhere in your page:

     <script src="https://sdk.inbenta.io/search/<version>/inbenta-search-client.js"></script>
  2. Creation

    Next, initialize the JS-Client. To do so, you will need a Domain Key and and API Key. Alternatively, you will need your API Key (public key) and either an API secret or an access token. See Finding your API credentials in the Help Center to obtain your credentials.

    The following example shows a creation using a domain key. For more information, see the Authorization section.

      var client = InbentaSearchClient.createFromDomainKey('<your_Domain_Key>', '<your_API_Key>');
  3. Use client

    client.search('toys').then(function(results) {
        console.log(results[0]);
    });

Example

The following code provides an example of how to do a search query using the Search JS-Client.

<!doctype html>
<html lang="en">
<head>
    <script src="https://sdk.inbenta.io/search/<version>/inbenta-search-client.js"></script>
</head>
<body>
  <script type="text/javascript">
    var domainKey = '<your_Domain_Key>';
    var apiKey = 'BVkiK9F7inLwEBEIUVrfpJhpOfjIfj8PyTVCiKu9WUs=';
    var client = InbentaSearchClient.createFromDomainKey(<your_Domain_Key>, <your_API_Key>);
    client.search('toys').then(function(results) {
        console.log(results[0]);
    });
  </script>
</body>

Versions

When you set up the Search JS-Client for your Inbenta product, you need to specify the version like this:

<script src="https://sdk.inbenta.io/search/<version>/inbenta-search-client.js"></script>

Versions are written in MAJOR.MINOR.PATCH format.

Important

• Do NOT cache or store these files, otherwise you will not benefit from bug fixing and minor upgrades.

• Inbenta strongly recommends that you use a MAJOR.MINOR.PATCH version.

Examples

  • If only MAJOR is set, this script will use the highest available MINOR version. <script src="https://sdk.inbenta.io/search/1/inbenta-search-sdk.js"></script>
  • If MAJOR.MINOR are set, this script will use the highest available PATCH version. <script src="https://sdk.inbenta.io/search/1.2/inbenta-search-sdk.js"></script>
  • If you specify the full version, only this exact version will be used. <script src="https://sdk.inbenta.io/search/1.2.3/inbenta-search-sdk.js"></script>

Client Creation explanation

Initialize your Search JS-Client using your API key and API secret or access token. To do so, see Finding your API credentials in the Help Center to obtain your credentials. These credentials are project-specific. For more information, see the Authorization section.

Important

Inbenta strongly recommends that you generate the access token on the server side. Never publish your API secret on your site. This could cause a security risk.

Initialize your Search JS-Client using an access token as follows:

var client = InbentaSearchClient.createFromAccessToken(accessToken: String, apiKey: String, config: Object);

Configuration

The following table shows the available InbentaSearchSDK parameters:

Name Type Default Description 
userType integer 0 Defines the profiles identifier from the Search App's knowledge base. It uses an x-inbenta-user-type header to make API requests. For more information about this header, see the API Routes.
environment string production Defines the source environment from the Search App's knowledge base. It will be used as x-inbenta-env header. Possible values:
  • production (default): This environment logs the data for the reports displayed in the Inbenta dashboards and retrieves the contents/categories published in live.
  • preproduction: This environment does not log any data and retrieves the contents/categories published in live.
  • development: This environment does not log any data and retrieves the contents/categories published in edit.
For more information about this header, see the API Routes.
apiURL string null Defines the URL of the search endpoint. If defined, it avoids the initial request to /apis for the sole purpose of getting the URL of the search endpoint when creating the Client using createFromAccessToken.
expirationTime integer null Defines the Unix timestamp when the token should expire. If defined, it avoids the initial request to /refreshToken when creating the Client using createFromAccessToken.
autoRefresh boolean true Defines whether or not the client gets a new token when the current one expires. If set to false, the client does not automatically call /refreshToken or /auth when the token expires.
connectionEntryPoint string https://api.inbenta.io/ This parameter defines the Inbenta API endpoint where the SDK is going to perform the Auth connection. You can select any available endpoint from the ones defined in Regions and Endpoints.

Methods

The following methods are available in the client:

Method Description
autocompleterData() Value for dynamic settings marked as autocompletable, or visible in the typeahead autocomplete. This can be done in the Knowledge Management App, from Settings > Dynamic.
generateSession() Creates a sessionToken (returns a promise).
hasSession() Whether or not the session is started.
hasError() Whether or not there is an authentication error.
isReady() Whether or not the client is ready, meaning, it has authenticated and retrieved the api endpoint correctly.
getAccessToken() Current access token.
getExpiration() Client's access token expiration period.
getExtraData() Application-related data defined in the knowledge base. More information here.
refreshAccessToken() Refresh the accessToken and receive a new access token (returns a promise).
setSession(sessionToken: String) Set up a session token into the client to track events (returns a promise).
setUserInfo(data: Object) Register specific user information for later analysis.
search(query: String, options: Object) Searches a single query with different options (returns a promise). More information here.
searches(requests: RequestOptions[]) Does multiple requests with different options (returns a promise). More information here.
trackEvent(event: String, data: Object) Tracks an event. More information here.
detectLanguage(query: String, data: Object) Retrieve the language of a user question. More information here.

Storage

By default, our SDK stores data related to sessions, authentication and APIs, as well as autocompleter data in localStorage. However, if you want to store data elsewhere or read data from a different type of storage, you can use the sdk.client.storageClient object to override the functions that store and read information in/from localStorage. The functions that can be overridden to change storage management are:

  • set: (key, expiresIn, value): Function responsible for storing information. By default, it stores the information in localStorage.

  • get: (key): Function responsible for retrieving information from storage. By default, it retrieves the information from localStorage.

  • clear: (): Function responsible for clearing the stored information. By default, it clears the information stored in localStorage.

The example below shows how to alter the storageClient object to store SDK data in sessionStorage:

// Override functions that currently store and read information in/from `localStorage` to store and read from `sessionStorage`.
sdk.client.storageClient = {
    set: (key, expiresIn, value) => {
        sessionStorage.setItem(key, JSON.stringify({
            value,
            expiresAt: Date.now() + expiresIn,
        }))
    },
    get: (key) => {
        let data = sessionStorage.getItem(key);
        if (!data) {
            return "{}";
        } else {
            return data;
        }
        if (this.has(key)) {
            return JSON.parse(sessionStorage.getItem(key)).value
        }
    },
    clear: () => {
        sessionStorage.clear()
    },
};

Handling Errors

Click here to see a list of Inbenta error codes.

// Search example
client.search('toys', [
  {
    filters: ['color:red', 'year:2017'],
    attributes: ['name', 'color', 'year']
  }
]).then(function (results) {
  console.log(results[0]);
}).catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

Managing authentication errors

The JS-Client launches an event when something goes wrong during the authentication process, or when the refreshToken request fails.

The name of the event is error. You can catch it easily like this:

client.on('error', function (error) {
    if (error.response.status === 403 ) {
       console.log('Error : ' + error.response.data.message);
    }
})