-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (69 loc) · 2.09 KB
/
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
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
const http = require('http');
const queryString = require('querystring');
class BosonNLP {
constructor({ apiToken = '', timeout = 1000 * 10 }) {
if (!apiToken) throw Error('The api token is required');
this.config = {
timeout
};
this.httpOptions = {
host : "api.bosonnlp.com",
port : 80,
method : "POST",
headers : {
"Content-Type" : "application/json",
"Accept" : "application/json",
"X-Token" : apiToken,
}
};
this.apis = {
'tag' : '/tag/analysis',
'sentiment' : '/sentiment/analysis',
'ner' : '/ner/analysis',
'depparser' : '/depparser/analysis',
'keywords' : '/keywords/analysis',
'classify' : '/classify/analysis',
'suggest' : '/suggest/analysis',
'time' : '/time/analysis',
'summary' : '/summary/analysis',
};
Object.keys(this.apis)
.forEach(key => {
this[key] = ((text, query) => {
let action = this.apis[key];
query && (action += `?${queryString.stringify(query)}`);
const options = Object.assign({}, this.httpOptions, { path : action });
return this.request(options, JSON.stringify(text));
});
});
}
request(options, body) {
const timeout = this.config.timeout;
const handle = (resolve, reject) => {
let data = new String();
const req = http.request(options, res => {
res.setEncoding('utf8');
res.on('data', chunk => {data += chunk});
res.on('end', () => {
try {
const _data = JSON.parse(data);
return resolve(_data);
} catch (err) {
return reject(err);
}
});
});
req.on('error', err => reject(new Error(err)));
req.on('socket', socket => {
socket.setTimeout(timeout);
socket.on('timeout',()=>{
req.abort();
return reject('Time out.');
});
});
req.end(body);
};
return new Promise(handle);
}
}
module.exports = BosonNLP;