-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdictionary.js
98 lines (80 loc) · 3.34 KB
/
dictionary.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
var DEBUG = false;
// Endpoints
var MW_ROOT = 'http://www.dictionaryapi.com/api/v1/references/collegiate/xml/';
// Dependencies
var request = require('request'),
xml = require('xml2js');
// Dictionary constructor
var Dictionary = function (config) {
this.key = config.key;
}
// Dictionary functions
Dictionary.prototype = {
//returns a word's definition
define: function(word, callback){
this.raw(word, function(error, result){
if (error === null) {
if (DEBUG) {
console.log('result', JSON.stringify(result, null, 2));
}
var results = [];
if (result.entry_list.entry != undefined) {
var entries = result.entry_list.entry;
for (var i=0; i<entries.length; i++){
//remove erroneous results (doodle != Yankee Doodle)
if (entries[i].ew == word) {
//construct a more digestable object
var definition = [];
var definition = entries[i].def[0].dt;
var partOfSpeech = entries[i].fl;
if (DEBUG) {
console.log('definition', JSON.stringify(definition, null, 2));
console.log('partOfSpeech', partOfSpeech);
}
results.push({
partOfSpeech: entries[i].fl,
definition: entries[i].def[0].dt.map(entry => {
if (typeof(entry) === 'string') {
return entry;
}
if (entry['_']) {
return entry['_'];
}
}).join('\n')
});
}
}
callback(null, results.filter(entry => entry.definition));
}
else if (result.entry_list.suggestion != undefined) {
callback('suggestions', result.entry_list.suggestion);
}
}
else callback(error);
});
},
//return a javascript object equivalent to the XML response from M-W
raw: function(word, callback){
var url = this.getSearchUrl(word);
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
xml.parseString(body, function(error, result){
if (error === null) callback(null, result);
else if (response.statusCode != 200) console.log(response.statusCode);
else {
console.log(error);
console.log('url: ' + url);
console.log('body: ' + body);
callback('XML Parsing error.');
}
});
}
else callback('API connection error.')
});
},
//constructs the search url
getSearchUrl: function(word){
return MW_ROOT+word+'?key='+this.key;
}
}
module.exports = Dictionary;