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

49 lines
1.0 KiB
TypeScript
Raw Normal View History

2024-04-23 16:45:06 -07:00
import axios from "axios";
import dotenv from "dotenv";
2024-04-24 10:11:01 -07:00
import { SearchResult } from "../../src/lib/entities";
2024-04-23 16:45:06 -07:00
dotenv.config();
2024-12-11 19:46:11 -03:00
export async function serper_search(
q,
options: {
tbs?: string;
filter?: string;
lang?: string;
country?: string;
location?: string;
num_results: number;
page?: number;
2024-12-11 19:46:11 -03:00
}
): Promise<SearchResult[]> {
2024-04-23 16:45:06 -07:00
let data = JSON.stringify({
q: q,
hl: options.lang,
gl: options.country,
location: options.location,
tbs: options.tbs,
num: options.num_results,
2024-12-11 19:46:11 -03:00
page: options.page ?? 1
2024-04-23 16:45:06 -07:00
});
let config = {
method: "POST",
url: "https://google.serper.dev/search",
headers: {
"X-API-KEY": process.env.SERPER_API_KEY,
2024-12-11 19:46:11 -03:00
"Content-Type": "application/json"
2024-04-23 16:45:06 -07:00
},
2024-12-11 19:46:11 -03:00
data: data
2024-04-23 16:45:06 -07:00
};
const response = await axios(config);
if (response && response.data && Array.isArray(response.data.organic)) {
2024-04-24 10:11:01 -07:00
return response.data.organic.map((a) => ({
url: a.link,
title: a.title,
2024-12-11 19:46:11 -03:00
description: a.snippet
2024-04-24 10:11:01 -07:00
}));
2024-12-11 19:46:11 -03:00
} else {
2024-04-23 16:45:06 -07:00
return [];
}
}