-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
90 lines (76 loc) · 2.79 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
88
89
90
const axios = require('axios');
class wordsextractorWrapper {
constructor(options) {
if (!options || typeof options !== 'object') {
throw new Error('Options object must be provided.');
}
const { api_key, secure = true } = options;
if (!api_key || typeof api_key !== 'string') {
throw new Error('API key must be provided as a non-empty string.');
}
if (typeof secure !== 'boolean') {
throw new Error('Secure parameter must be a boolean value.');
}
this.APIKey = api_key;
this.IsSecure = secure;
// secure is deprecated, all requests must be made over HTTPS
this.baseURL = 'https://api.apiverve.com/v1/wordsextractor';
}
async execute(query, callback) {
if(arguments.length > 1) {
if (!query || typeof query !== 'object') {
throw new Error('Query parameters must be provided as an object.');
}
} else {
callback = query;
query = {};
}
var requiredParams = ["text", "partofspeech"];
if (requiredParams.length > 0) {
for (var i = 0; i < requiredParams.length; i++) {
if (!query[requiredParams[i]]) {
throw new Error(`Required parameter [${requiredParams[i]}] is missing.`);
}
}
}
const method = 'POST';
const url = method === 'POST' ? this.baseURL : this.constructURL(query);
try {
const response = await axios({
method,
url,
headers: {
'Content-Type': 'application/json',
'x-api-key': this.APIKey,
'auth-mode': 'npm-package'
},
data: method === 'POST' ? query : undefined
});
const data = response.data;
callback(null, data);
return data;
} catch (error) {
if (error.response.data) {
callback(error.response.data, null);
throw error.response.data;
} else {
callback(error, null);
throw error;
}
}
}
constructURL(query) {
let url = this.baseURL;
if(query && typeof query === 'object')
{
if (Object.keys(query).length > 0) {
const queryString = Object.keys(query)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`)
.join('&');
url += `?${queryString}`;
}
}
return url;
}
}
module.exports = wordsextractorWrapper;