-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
209 lines (176 loc) · 8.04 KB
/
index.js
File metadata and controls
209 lines (176 loc) · 8.04 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
const axios = require('axios');
class textsimilarityWrapper {
constructor(options) {
if (!options || typeof options !== 'object') {
throw new Error('Options object must be provided. See documentation: https://docs.apiverve.com/ref/textsimilarity');
}
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. Get your API key at: https://apiverve.com');
}
// Validate API key format (GUID, prefixed keys like apv_xxx, or alphanumeric)
const apiKeyPattern = /^[a-zA-Z0-9_-]+$/;
if (!apiKeyPattern.test(api_key)) {
throw new Error('Invalid API key format. API key must be alphanumeric and may contain hyphens and underscores. Get your API key at: https://apiverve.com');
}
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/textsimilarity';
// Validation rules for parameters (generated from schema)
this.validationRules = {"text1":{"type":"string","required":true},"text2":{"type":"string","required":true}};
}
/**
* Validate query parameters against schema rules
* @param {Object} query - The query parameters to validate
* @throws {Error} - If validation fails
*/
validateParams(query) {
const errors = [];
for (const [paramName, rules] of Object.entries(this.validationRules)) {
const value = query[paramName];
// Check required
if (rules.required && (value === undefined || value === null || value === '')) {
errors.push(`Required parameter [${paramName}] is missing.`);
continue;
}
// Skip validation if value is not provided and not required
if (value === undefined || value === null) {
continue;
}
// Type validation
if (rules.type === 'integer' || rules.type === 'number') {
const numValue = Number(value);
if (isNaN(numValue)) {
errors.push(`Parameter [${paramName}] must be a valid ${rules.type}.`);
continue;
}
if (rules.type === 'integer' && !Number.isInteger(numValue)) {
errors.push(`Parameter [${paramName}] must be an integer.`);
continue;
}
// Min/max validation for numbers
if (rules.min !== undefined && numValue < rules.min) {
errors.push(`Parameter [${paramName}] must be at least ${rules.min}.`);
}
if (rules.max !== undefined && numValue > rules.max) {
errors.push(`Parameter [${paramName}] must be at most ${rules.max}.`);
}
} else if (rules.type === 'string') {
if (typeof value !== 'string') {
errors.push(`Parameter [${paramName}] must be a string.`);
continue;
}
// Length validation for strings
if (rules.minLength !== undefined && value.length < rules.minLength) {
errors.push(`Parameter [${paramName}] must be at least ${rules.minLength} characters.`);
}
if (rules.maxLength !== undefined && value.length > rules.maxLength) {
errors.push(`Parameter [${paramName}] must be at most ${rules.maxLength} characters.`);
}
// Format validation
if (rules.format) {
const formatPatterns = {
'email': /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
'url': /^https?:\/\/.+/i,
'ip': /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$|^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/,
'date': /^\d{4}-\d{2}-\d{2}$/,
'hexColor': /^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/
};
if (formatPatterns[rules.format] && !formatPatterns[rules.format].test(value)) {
errors.push(`Parameter [${paramName}] must be a valid ${rules.format}.`);
}
}
} else if (rules.type === 'boolean') {
if (typeof value !== 'boolean' && value !== 'true' && value !== 'false') {
errors.push(`Parameter [${paramName}] must be a boolean.`);
}
} else if (rules.type === 'array') {
if (!Array.isArray(value)) {
errors.push(`Parameter [${paramName}] must be an array.`);
}
}
// Enum validation
if (rules.enum && Array.isArray(rules.enum)) {
if (!rules.enum.includes(value)) {
errors.push(`Parameter [${paramName}] must be one of: ${rules.enum.join(', ')}.`);
}
}
}
if (errors.length > 0) {
throw new Error(`Validation failed: ${errors.join(' ')} See documentation: https://docs.apiverve.com/ref/textsimilarity`);
}
}
async execute(query, callback) {
// Handle different argument patterns
if(arguments.length === 0) {
// execute() - no args
query = {};
callback = null;
} else if(arguments.length === 1) {
if (typeof query === 'function') {
// execute(callback)
callback = query;
query = {};
} else {
// execute(query)
callback = null;
}
} else {
// execute(query, callback)
if (!query || typeof query !== 'object') {
throw new Error('Query parameters must be provided as an object.');
}
}
// Validate parameters against schema rules
this.validateParams(query);
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;
if (callback) callback(null, data);
return data;
} catch (error) {
let apiError;
if (error.response && error.response.data) {
apiError = error.response.data;
} else if (error.message) {
apiError = { error: error.message, status: 'error' };
} else {
apiError = { error: 'An unknown error occurred', status: 'error' };
}
if (callback) {
callback(apiError, null);
return; // Don't throw if callback is provided
}
throw apiError;
}
}
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 = textsimilarityWrapper;