-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.mjs
More file actions
83 lines (72 loc) · 2.71 KB
/
Copy pathindex.mjs
File metadata and controls
83 lines (72 loc) · 2.71 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
export class IbanValidatorClient {
constructor(config = {}) {
this.apiKey = config.apiKey || (typeof process !== 'undefined' ? process.env?.STANZA_API_KEY || process.env?.API_KEY || '' : '');
this.timeoutMs = config.timeoutMs || 15000;
this.tier = config.tier || 'sandbox';
this.baseUrl = config.baseUrl || 'https://api.stanzaapi.com/iban-validator';
this.validateEndpoint = '/api/v1/validate';
this.parseEndpoint = '/api/v1/validate';
this.toolUrl = 'https://stanzaapi.com/tools/iban-validator';
}
async request(endpoint, options = {}) {
const cleanBase = this.baseUrl.replace(/\/+$/, '');
const cleanPath = endpoint.replace(/^\/+/, '');
const url = `${cleanBase}/${cleanPath}`;
const headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
...(this.apiKey ? { 'x-api-key': this.apiKey, 'Authorization': `Bearer ${this.apiKey}` } : {}),
...(options.headers || {})
};
let signal = options.signal;
if (!signal && typeof AbortSignal !== 'undefined' && AbortSignal.timeout) {
signal = AbortSignal.timeout(this.timeoutMs);
}
try {
const response = await fetch(url, { ...options, headers, signal });
const text = await response.text();
let data;
try {
data = JSON.parse(text);
} catch {
data = {
success: false,
error: `HTTP ${response.status}: ${response.statusText || text.slice(0, 180)}`,
code: response.status === 429 ? 'RATE_LIMITED' : response.status === 413 ? 'PAYLOAD_TOO_LARGE' : 'HTTP_ERROR',
};
}
if (typeof data === 'object' && data !== null) {
data.tool_url = data.tool_url || this.toolUrl;
data.upgrade_url = data.upgrade_url || this.toolUrl;
}
return data;
} catch (err) {
const isTimeout = err?.name === 'TimeoutError';
return {
success: false,
error: isTimeout ? `Request timed out after ${this.timeoutMs}ms` : (err?.message || 'Network request failed'),
code: isTimeout ? 'TIMEOUT' : 'NETWORK_ERROR',
tool_url: this.toolUrl,
upgrade_url: this.toolUrl
};
}
}
async getHealth() {
return this.request('/health', { method: 'GET' });
}
async validate(payload) {
const body = typeof payload === 'string' ? JSON.stringify({ input: payload }) : JSON.stringify(payload);
return this.request(this.validateEndpoint, {
method: 'POST',
body
});
}
async parse(payload) {
const body = typeof payload === 'string' ? JSON.stringify({ input: payload }) : JSON.stringify(payload);
return this.request(this.parseEndpoint, {
method: 'POST',
body
});
}
}
export default IbanValidatorClient;