export const fetchWikipediaContent = async (req: Request) => {
const url = new URL(req.url);
const title = url.searchParams.get("title");
if (!title) {
return new Response("Title parameter is required", {
status: 400,
headers: { "Content-Type": "text/plain" },
});
}
try {
const apiUrl =
`https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro&explaintext&format=json&origin=*&titles=${
encodeURIComponent(title)
}`;
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
const pageId = Object.keys(data.query.pages)[0];
if (pageId === "-1") {
return new Response("No content found for the provided title", {
status: 404,
headers: { "Content-Type": "text/plain" },
});
}
const content = data.query.pages[pageId].extract;
return new Response(content, {
status: 200,
headers: { "Content-Type": "text/plain" },
});
} catch (error) {
return new Response(`Error fetching Wikipedia content: ${error.message}`, {
status: 500,
headers: { "Content-Type": "text/plain" },
});
}
};