Files
firecrawl/apps/api/src/search/searchapi.ts
T

63 lines
1.4 KiB
TypeScript
Raw Normal View History

2024-09-03 18:26:11 +03:00
import axios from "axios";
import dotenv from "dotenv";
import { SearchResult } from "../../src/lib/entities";
dotenv.config();
interface SearchOptions {
tbs?: string;
filter?: string;
lang?: string;
country?: string;
location?: string;
num_results: number;
page?: number;
}
2024-12-11 19:46:11 -03:00
export async function searchapi_search(
q: string,
options: SearchOptions
): Promise<SearchResult[]> {
2024-09-03 18:26:11 +03:00
const params = {
q: q,
hl: options.lang,
gl: options.country,
location: options.location,
num: options.num_results,
page: options.page ?? 1,
2024-12-11 19:46:11 -03:00
engine: process.env.SEARCHAPI_ENGINE || "google"
2024-09-03 18:26:11 +03:00
};
const url = `https://www.searchapi.io/api/v1/search`;
try {
const response = await axios.get(url, {
headers: {
2024-12-11 19:46:11 -03:00
Authorization: `Bearer ${process.env.SEARCHAPI_API_KEY}`,
2024-09-03 18:26:11 +03:00
"Content-Type": "application/json",
2024-12-11 19:46:11 -03:00
"X-SearchApi-Source": "Firecrawl"
2024-09-03 18:26:11 +03:00
},
2024-12-11 19:46:11 -03:00
params: params
2024-09-03 18:26:11 +03:00
});
if (response.status === 401) {
throw new Error("Unauthorized. Please check your API key.");
}
const data = response.data;
if (data && Array.isArray(data.organic_results)) {
return data.organic_results.map((a: any) => ({
url: a.link,
title: a.title,
2024-12-11 19:46:11 -03:00
description: a.snippet
2024-09-03 18:26:11 +03:00
}));
} else {
return [];
}
} catch (error) {
console.error(`There was an error searching for content: ${error.message}`);
return [];
}
}