/ docs-website / api / search.ts
search.ts
 1  import { VercelRequest, VercelResponse } from "@vercel/node";
 2  
 3  export default async function handler(req: VercelRequest, res: VercelResponse) {
 4    if (req.method !== "POST") {
 5      res.setHeader("Allow", "POST");
 6      return res.status(405).end("Method Not Allowed");
 7    }
 8  
 9    const { query, filter } = req.body;
10  
11    if (!query) {
12      return res.status(400).json({ error: "Query is required" });
13    }
14  
15    const { SEARCH_API_WORKSPACE, SEARCH_API_PIPELINE, SEARCH_API_TOKEN } =
16      process.env;
17  
18    if (!SEARCH_API_WORKSPACE || !SEARCH_API_PIPELINE || !SEARCH_API_TOKEN) {
19      console.error(
20        "Search API environment variables are not configured on the server."
21      );
22      return res.status(500).json({ error: "Search service is not configured." });
23    }
24  
25    try {
26      // Build the request body with optional filters
27      const requestBody: any = {
28        queries: [query],
29      };
30  
31      // Add filters if provided (for future backend filtering support)
32      if (filter && filter !== "all") {
33        requestBody.debug = true;
34        requestBody.filters = {
35          operator: "AND",
36          conditions: [
37            {
38              field: "meta.type",
39              operator: "==",
40              value: filter,
41            },
42          ],
43        };
44      }
45  
46      const apiResponse = await fetch(
47        `https://api.cloud.deepset.ai/api/v1/workspaces/${SEARCH_API_WORKSPACE}/pipelines/${SEARCH_API_PIPELINE}/search`,
48        {
49          method: "POST",
50          headers: {
51            "Content-Type": "application/json",
52            "X-Client-Source": "haystack-docs",
53            Authorization: `Bearer ${SEARCH_API_TOKEN}`,
54          },
55          body: JSON.stringify(requestBody),
56        }
57      );
58  
59      if (!apiResponse.ok) {
60        const errorData = await apiResponse.text();
61        console.error("Haystack API error:", errorData);
62        return res
63          .status(apiResponse.status)
64          .json({ error: `API error: ${apiResponse.statusText}` });
65      }
66  
67      const data = await apiResponse.json();
68      return res.status(200).json(data);
69    } catch (error) {
70      console.error("Internal server error:", error);
71      return res.status(500).json({ error: "Failed to fetch search results." });
72    }
73  }