Back

Version 28

2/16/2024
// Fixed and improved version of searchClosestWiki
import { fetch } from "https://esm.town/v/std/fetch";

export const searchClosestWiki = async (req: Request) => {
const searchQuery = new URL(req.url).searchParams.get("query"); // Corrected from "format" to "query"

if (!searchQuery) {
return new Response("Invalid input. Please provide a search query via ?query= parameter.", {
status: 400, // Bad Request
headers: { "Content-Type": "text/plain" },
});
}

try {
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) {
return new Response(`No Wikipedia article found for "${searchQuery}"`, {
status: 404, // Not Found
headers: { "Content-Type": "text/plain" },
});
}

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;

jamiedubs-searchwikipedia.web.val.run
Updated: February 16, 2024