forked from dachev/node-cld
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
87 lines (76 loc) · 2.24 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
79
80
81
82
83
84
85
86
87
const _ = require('underscore');
const cld2 = require('./build/Release/cld');
module.exports = {
LANGUAGES : cld2.LANGUAGES,
DETECTED_LANGUAGES : cld2.DETECTED_LANGUAGES,
ENCODINGS : cld2.ENCODINGS,
async detect(text, options) {
let cb = arguments[2];
if (typeof cb !== 'function' && typeof options === 'function') {
cb = options;
options = {};
}
try {
if (arguments.length < 1) {
throw new Error('Not enough arguments provided');
}
if (!_.isString(text) || text.length < 1) {
throw new Error('Empty or invalid text');
}
const defaults = {
isHTML : false,
languageHint : '',
encodingHint : '',
tldHint : '',
httpHint : ''
};
options = _.defaults({}, options, defaults);
if (!_.isBoolean(options.isHTML)) {
throw new Error('Invalid isHTML value');
}
if (!_.isString(options.languageHint)) {
throw new Error('Invalid languageHint');
}
if (!_.isString(options.encodingHint)) {
throw new Error('Invalid encodingHint');
}
if (!_.isString(options.tldHint)) {
throw new Error('Invalid tldHint');
}
if (!_.isString(options.httpHint)) {
throw new Error('Invalid httpHint');
}
if (options.encodingHint.length > 0 &&
!~cld2.ENCODINGS.indexOf(options.encodingHint)) {
throw new Error('Invalid encodingHint, see ENCODINGS');
}
if (options.languageHint.length > 0 &&
!~_.keys(cld2.LANGUAGES).indexOf(options.languageHint) &&
!~_.values(cld2.LANGUAGES).indexOf(options.languageHint)) {
throw new Error('Invalid languageHint, see LANGUAGES');
}
const result = await cld2.detectAsync(
text,
!options.isHTML,
options.languageHint,
options.encodingHint,
options.tldHint,
options.httpHint
);
if (result.languages.length < 1) {
throw new Error('Failed to identify language');
}
if (cb) {
return cb(null, result);
} else {
return result;
}
} catch (error) {
if (cb) {
cb(error);
} else {
throw error;
}
}
}
};