Spaces:
Sleeping
Sleeping
File size: 937 Bytes
2c00ea8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import { env } from "$env/dynamic/private";
import { isURL } from "$lib/utils/isUrl";
import type { WebSearchSource } from "$lib/types/WebSearch";
type SerpStackResponse = {
organic_results: {
title: string;
url: string;
snippet?: string;
}[];
error?: string;
};
export default async function searchSerpStack(query: string): Promise<WebSearchSource[]> {
const response = await fetch(
`http://api.serpstack.com/search?access_key=${env.SERPSTACK_API_KEY}&query=${query}&hl=en&gl=us`,
{ headers: { "Content-type": "application/json; charset=UTF-8" } }
);
const data = (await response.json()) as SerpStackResponse;
if (!response.ok) {
throw new Error(
data.error ?? `SerpStack API returned error code ${response.status} - ${response.statusText}`
);
}
return data.organic_results
.filter(({ url }) => isURL(url))
.map(({ title, url, snippet }) => ({
title,
link: url,
text: snippet ?? "",
}));
}
|