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
37
import { fetch } from "https://esm.town/v/std/fetch";
export const searchClosestWiki = async (searchQuery) => {
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;
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;
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(textContent, "text/html");
const extractedText = htmlDoc.querySelector("body").textContent;
return `${extractedText.trim()}`;
} catch (error) {
console.log("Error fetching Wikipedia content:", error);
return `An error occurred while fetching the Wikipedia content. ${error}`;
}
};
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
October 23, 2023