-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
wikipedia.js
119 lines (101 loc) · 3.44 KB
/
wikipedia.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import { json as d3_json } from 'd3-fetch';
import { utilQsString } from '../util';
var endpoint = 'https://en.wikipedia.org/w/api.php?';
export default {
init: function() {},
reset: function() {},
search: function(lang, query, callback) {
if (!query) {
if (callback) callback('No Query', []);
return;
}
lang = lang || 'en';
var url = endpoint.replace('en', lang) +
utilQsString({
action: 'query',
list: 'search',
srlimit: '10',
srinfo: 'suggestion',
format: 'json',
origin: '*',
srsearch: query
});
d3_json(url)
.then(function(result) {
if (result && result.error) {
throw new Error(result.error);
} else if (!result || !result.query || !result.query.search) {
throw new Error('No Results');
}
if (callback) {
var titles = result.query.search.map(function(d) { return d.title; });
callback(null, titles);
}
})
.catch(function(err) {
if (callback) callback(err, []);
});
},
suggestions: function(lang, query, callback) {
if (!query) {
if (callback) callback('', []);
return;
}
lang = lang || 'en';
var url = endpoint.replace('en', lang) +
utilQsString({
action: 'opensearch',
namespace: 0,
suggest: '',
format: 'json',
origin: '*',
search: query
});
d3_json(url)
.then(function(result) {
if (result && result.error) {
throw new Error(result.error);
} else if (!result || result.length < 2) {
throw new Error('No Results');
}
if (callback) callback(null, result[1] || []);
})
.catch(function(err) {
if (callback) callback(err.message, []);
});
},
translations: function(lang, title, callback) {
if (!title) {
if (callback) callback('No Title');
return;
}
var url = endpoint.replace('en', lang) +
utilQsString({
action: 'query',
prop: 'langlinks',
format: 'json',
origin: '*',
lllimit: 500,
titles: title
});
d3_json(url)
.then(function(result) {
if (result && result.error) {
throw new Error(result.error);
} else if (!result || !result.query || !result.query.pages) {
throw new Error('No Results');
}
if (callback) {
var list = result.query.pages[Object.keys(result.query.pages)[0]];
var translations = {};
if (list && list.langlinks) {
list.langlinks.forEach(function(d) { translations[d.lang] = d['*']; });
}
callback(null, translations);
}
})
.catch(function(err) {
if (callback) callback(err.message);
});
}
};