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
38
39
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, // Bad Request
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, // Not Found
headers: { "Content-Type": "text/plain" },
});
}
return new Response(JSON.stringify(data.query.pages[pageId]), {
status: 200, // OK
headers: { "Content-Type": "text/json" },
});
} catch (error) {
return new Response(`Error fetching Wikipedia content: ${error.message}`, {
status: 500, // Internal Server Error
headers: { "Content-Type": "text/plain" },
});
}
};