-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
52 lines (44 loc) · 1004 Bytes
/
index.js
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
41
42
43
44
45
46
47
48
49
50
51
52
const defaultUnwantedProps = [
'content_urls',
'dir',
'revision',
'tid',
'timestamp',
'pageid',
'namespace',
'titles',
'api_urls'
]
async function lookup (
query,
locale = 'en',
followRedirects = false,
unwantedProps = defaultUnwantedProps
) {
const url = new URL(`https://${locale}.wikipedia.org`)
const params = { followRedirects }
url.pathname = `/api/rest_v1/page/summary/${encodeURIComponent(query)}`
url.search = new URLSearchParams(params).toString()
let body
try {
const res = await fetch(url).then(res => {
if (!res.ok) {
throw Error(res.statusText)
}
return res
})
body = await res.json()
} catch (err) {
return null
}
unwantedProps.forEach(prop => {
delete body[prop]
})
if (body.text) {
body.text = body.text
.trim()
.replace(/\[\d+\]/g, '')
} // remove footnotes like [1]
if (body.html) body.html = body.html.trim()
return Object.assign({}, { query: query }, body)
}