-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoogle_suggest.js
55 lines (48 loc) · 1.4 KB
/
google_suggest.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
let convert = require('xml-js');
Array.prototype.randomElement = function () {
return this[Math.floor(Math.random() * this.length)]
}
let parseXml = function (xml) {
let jsonResponse = convert.xml2json(xml, {compact: true, spaces: 4});
json = JSON.parse(jsonResponse)
return generateSuggestion(json)
}
let generateSuggestion = function (json) {
let answer = null
let suggestions = json.toplevel.CompleteSuggestion
if (suggestions && suggestions.length > 0) {
let suggestionJson = suggestions[Math.floor(Math.random()*suggestions.length)]
answer = suggestionJson.suggestion["_attributes"].data
}
return answer
}
let fetchXml = function (url) {
return fetch(url).then(function(response) {
return response.text()
})
.then(function(xml) {
return parseXml(xml);
})
}
let generateUrl = function (query, word) {
if (query.split(" ").length > 0) {
query = query.split(" ").join("%20")
}
return url = `http://clients1.google.com/complete/search?hl=en&output=toolbar&q=${query}%20${word}%20`
}
let makeRequest = function (query) {
let words = ['is', 'are', 'can', 'will']
let url = generateUrl(query, words.randomElement());
let urlTwo = generateUrl(query, words.randomElement());
let result = fetchXml(url);
if (result) {
return result
} else {
return fetchXml(urlTwo);
}
}
module.exports = {
new: function(query) {
return makeRequest(query);
}
}