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
40
import { fetch } from "https://esm.town/v/std/fetch";
export async function fetchFromWikipedia(params) {
const endpoint = 'https://en.wikipedia.org/w/api.php';
const url = `${endpoint}?${new URLSearchParams(params).toString()}`;
try {
const response = await fetch(url);
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching Wikipedia data:', error);
}
}
export async function searchWikipedia(searchTerm, additionalParams = {}) {
const defaultParams = {
action: 'query',
list: 'search',
srsearch: searchTerm,
format: 'json'
};
const params = { ...defaultParams, ...additionalParams };
const data = await fetchFromWikipedia(params);
// Construct full URLs for each search result
if (data && data.query && data.query.search) {
const baseUrl = 'https://en.wikipedia.org/wiki/';
data.query.search = data.query.search.map(result => ({
...result,
fullUrl: `${baseUrl}${encodeURIComponent(result.title.replace(/ /g, '_'))}`
}));
}
return data;
}
// Example usage
// searchWikipedia('Svelte', { srlimit: 5 }).then(data => console.log(data));
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!
July 23, 2024