Skip to content

Commit

Permalink
fix the connect timeout does not work
Browse files Browse the repository at this point in the history
  • Loading branch information
peze committed Nov 6, 2024
1 parent 65e84c6 commit 574a129
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
8 changes: 8 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,14 @@ export function request(url, opts) {
});
}

request.on('timeout', () => {
var err = new Error();
err.name = 'RequestTimeoutError';
err.message = `ConnectTimeout: Connect ${url} failed.`;
request.destroy();
reject(err);
});

request.on('response', fulfilled);
request.on('error', rejected);
request.once('socket', function (socket) {
Expand Down
20 changes: 17 additions & 3 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ describe('httpx', () => {

it('timeout should ok', async function () {
try {
await make(server)('/timeout', {timeout: 100});
await make(server)('/timeout', {timeout: 1000});
} catch (ex) {
assert.strictEqual(ex.name, 'RequestTimeoutError');
const port = server.address().port;
Expand All @@ -219,9 +219,23 @@ describe('httpx', () => {
assert.ok(false, 'should not ok');
});

it('timeout(connectTimeout) should ok', async function () {
try {
await httpx.request('http://100.100.100.200', {
readTimeout: 1000,
connectTimeout: 1000
});
} catch (ex) {
assert.strictEqual(ex.name, 'RequestTimeoutError');
assert.strictEqual(ex.message, 'ConnectTimeout: Connect http://100.100.100.200 failed.');
return;
}
assert.ok(false, 'should not ok');
});

it('timeout(readTimeout) should ok', async function () {
try {
await make(server)('/readTimeout', {readTimeout: 100, connectTimeout: 50});
await make(server)('/readTimeout', {readTimeout: 100, connectTimeout: 1000});
} catch (ex) {
assert.strictEqual(ex.name, 'RequestTimeoutError');
const port = server.address().port;
Expand All @@ -233,7 +247,7 @@ describe('httpx', () => {

it('timeout(readTimeout & timeout) should ok', async function () {
try {
await make(server)('/readTimeout', {readTimeout: 100, connectTimeout: 50, timeout: 300});
await make(server)('/readTimeout', {readTimeout: 100, connectTimeout: 1000, timeout: 300});
} catch (ex) {
assert.strictEqual(ex.name, 'RequestTimeoutError');
const port = server.address().port;
Expand Down

0 comments on commit 574a129

Please sign in to comment.