typesense / typesense-instantsearch-adapter

A JS adapter library to build rich search interfaces with Typesense and InstantSearch.js
MIT License
361 stars 62 forks source link

Detecting empty search requests #158

Closed mcamprodon closed 1 year ago

mcamprodon commented 1 year ago

Description

I don’t want to perform a search request when the query is empty. With Algolia searchClient seems easy: https://www.algolia.com/doc/guides/building-search-ui/going-further/conditional-requests/react/#detecting-empty-search-requests

Can you explain me how to do the same with typesenseInstantsearchAdapter ?

jasonbosco commented 1 year ago

Following the example from your link, could you try something like this:


const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({...});
const typesenseAdapterSearchClient = typesenseInstantsearchAdapter.searchClient;

const searchClient = {
  ...typesenseAdapterSearchClient,
  search(requests) {
    if (requests.every(({ params }) => !params.query)) {
      // Here we have to do something else
    }

    return typesenseAdapterSearchClient.search(requests);
  },
};
mcamprodon commented 1 year ago

Perfect!

This is the complete function to return an empty response:

const searchClient = {
    ...typesenseAdapterSearchClient,
    search(requests) {
        if (requests.every(({ params }) => !params.query)) {
            return Promise.resolve({
                results: requests.map(() => ({
                    hits: [],
                    nbHits: 0,
                    nbPages: 0,
                    page: 0,
                    processingTimeMS: 0,
                    hitsPerPage: 0,
                    exhaustiveNbHits: false,
                    query: '',
                    params: '',
                })),
            })
        }

        return typesenseAdapterSearchClient.search(requests)
    },
}