forked from wzbg/textrazor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
92 lines (86 loc) · 2.55 KB
/
index.js
File metadata and controls
92 lines (86 loc) · 2.55 KB
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
/*
* @Author: zyc
* @Date: 2016-02-18 14:06:33
* @Last Modified by: Guik
* @Last Modified time: 2018-03-15 11:11:11
*/
'use strict'
var request = require('request')
const url = 'https://api.textrazor.com'
module.exports = class {
constructor(apiKey, headers) {
if (typeof apiKey === 'object') headers = apiKey
this.headers = headers = headers || {}
if (!headers['x-textrazor-key']) headers['x-textrazor-key'] = apiKey
if (!headers['Content-Type']) headers['Content-Type'] = 'text/html'
this.apiKey = headers['x-textrazor-key']
}
exec(text, options) {
if (typeof text === 'object') options = text
options = options || {}
options.extractors = options.extractors || 'entities'
if (options.text) text = options.text
if (options.maxConcurrentRequest){ //TextRazor API limit concurrent requests
request = request.defaults({pool: { maxSockets: options.maxConcurrentRequest}})
}
const maxLength = options.maxLength || 100000
const texts = []
if (text.length < maxLength) {
texts.push(text)
} else {
let tmpText = ''
for (let content of text.split(' ')) {
tmpText += content + ' '
if (tmpText.length > maxLength) {
texts.push(tmpText)
tmpText = ''
}
}
if (tmpText) texts.push(tmpText)
}
return new Promise((resolve, reject) => {
Promise.all(texts.map(text => {
options.text = text
return this.textrazor(options)
})).then(results => {
let json
for (let data of results) {
if (json) {
for(var k in data.response){
if (data.response[k] instanceof Array) {
if (json.response[k] === undefined) {
json.response[k] = [];
}
for (let d of data.response[k]) {
json.response[k].push(d)
}
}
}
} else {
json = data
}
}
resolve(json);
}).catch(err => reject(err))
})
}
textrazor(options) {
return new Promise((resolve, reject) => {
request.post(url, { headers: this.headers, form: options }, (err, resp, body) => {
if (err) return reject(err)
try {
const json = JSON.parse(body)
if (resp.statusCode === 200) {
resolve(json)
} else {
json.code = resp.statusCode
json.key = this.apiKey
reject(json)
}
} catch (err) {
reject(err)
}
})
})
}
}