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

Getting results in JSON format from SearchBox #206

Closed albavilanova closed 1 month ago

albavilanova commented 1 month ago

Description

Good evening,

I am using Typesense instant search in Next.js and would like to get the results from the SearchBox in JSON format instead as in the Hits component, so that I can send them through a custom GET request in an API endpoint and in that way avoid exposing my API key. Is it possible?

Thanks,

Alba

Steps to reproduce

My current code looks something like:

        <InstantSearch
          indexName="locations"
          searchClient={client}
        >
          <div className="mt-10 flex items-start justify-center">
            <div>
              Search value {searchValue}
              <SearchBox
                showLoadingIndicator={true}
                onChange={() => setShowHits(true)}
                // onBlur={()=>setShowHits(false)}
                className="w-[500px]"
                translations={{
                  placeholder: 'Escribe el nombre de tu ciudad...',
                }}
              />
              {showHits ? <Hits hitComponent={Location} /> : null}
            </div>
            <button
              className={cn(
                'grow-0 rounded border border-principal-purple',
                'bg-principal-purple px-4 font-bold text-white',
              )}
              onClick={() => router.push(url)}
            >
              Buscar
            </button>
          </div>
        </InstantSearch>

Metadata

Typesense Version:

OS: Ubuntu 20.04.6 LTS

jasonbosco commented 1 month ago

There is a tranformItems prop in the Hits widget that gives you an array of the current search results. May be you could use that?

albavilanova commented 1 month ago

Hi Jason,

Thank you, I wanted to get the results before getting into the Instant Search component. I figured it out in case somebody needs to do the same, in route.ts you can have:

import { NextRequest, NextResponse } from 'next/server';
import Typesense from 'typesense';

export async function GET(req: NextRequest, res: NextResponse) {

  const query = req.nextUrl.searchParams.get('query');
  const { TYPESENSE_API_KEY } = process.env;

  const client = new Typesense.Client({
    nodes: [
      {
        host: 'localhost',
        port: 8108,
        protocol: 'http',
      },
    ],
    apiKey: `${TYPESENSE_API_KEY}`,
    connectionTimeoutSeconds: 2,
  });

  const searchParameters = {
    q: query,
    query_by: 'name',
  };

  const results = await client
    .collections('locations')
    .documents()
    .search(searchParameters);

  return NextResponse.json(results);
}