Skip to content

Commit 6bf400f

Browse files
committed
Fix timeout handling
1 parent e788d40 commit 6bf400f

2 files changed

Lines changed: 18 additions & 2 deletions

File tree

src/client.js

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,20 +40,36 @@ export default class Client {
4040
});
4141
}
4242

43+
/**
44+
* Base request method that handles common request logic
45+
* @param {string} path - API endpoint path
46+
* @param {Object} options - Fetch options
47+
* @returns {Promise<Object>} Response data
48+
*/
4349
async request(path, options = {}) {
4450
try {
51+
const controller = new AbortController();
52+
const timeoutId = setTimeout(() => {
53+
controller.abort();
54+
}, this.timeout);
55+
4556
const response = await fetch(this.baseURL + path, {
4657
headers: this.headers,
47-
timeout: this.timeout,
58+
signal: controller.signal,
4859
...options,
4960
});
5061

62+
clearTimeout(timeoutId);
63+
5164
if (!response.ok) {
5265
throw new Error(await response.text());
5366
}
5467

5568
return await response.json();
5669
} catch (e) {
70+
if (e.name === 'AbortError') {
71+
throw new Error(`Request timeout after ${this.timeout}ms`);
72+
}
5773
return handleError(e);
5874
}
5975
}

src/defaults.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
const { version } = require('../package.json');
22

33
module.exports = {
4-
timeout: 60,
4+
timeout: 60, // seconds
55
protocol: 'https',
66
host: 'ws.detectlanguage.com',
77
apiVersion: 'v3',

0 commit comments

Comments
 (0)