Back

Version 6

4/10/2023
// export const searchClosestWiki = async (searchQuery: string) => {
export const searchClosestWiki = (async (searchQuery: string) => {
console.log("hi");
try {
if (!searchQuery) {
throw new Error(
"Invalid input. Please provide a search query as a string."
);
}
const { DOMParser } = await import(
"https://deno.land/x/deno_dom/deno-dom-wasm.ts"
);
const searchUrl = `https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=${encodeURIComponent(
searchQuery
)}&srwhat=text&format=json&utf8=1&origin=*`;
const searchResponse = await fetch(searchUrl);
const searchData = await searchResponse.json();
if (!searchData.query.search.length) {
throw new Error(`No Wikipedia article found for "${searchQuery}"`);
}
const pageTitle = searchData.query.search[0].title;
console.log({ pageTitle });
const contentUrl = `https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro&titles=${encodeURIComponent(
pageTitle
)}&format=json&utf8=1&origin=*`;
const contentResponse = await fetch(contentUrl);
const contentData = await contentResponse.json();
const pageId = Object.keys(contentData.query.pages)[0];
const textContent = contentData.query.pages[pageId].extract;
console.log({ textContent });
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(textContent, "text/html");
const extractedText = htmlDoc.querySelector("body").textContent;
console.log({ extractedText });
return `${extractedText.trim()}`;
} catch (error) {
jamiedubs-searchwikipedia.web.val.run
Updated: February 16, 2024