Skip to content

Commit 8d37edb

Browse files
committed
Fix timeout
1 parent d9a14e8 commit 8d37edb

3 files changed

Lines changed: 24 additions & 6 deletions

File tree

src/errors.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,10 @@ export class InvalidTimeoutError extends Error {
1313
Object.setPrototypeOf(this, InvalidTimeoutError.prototype);
1414
}
1515
}
16+
17+
export class RequestTimeoutError extends Error {
18+
constructor() {
19+
super("The request was timed out");
20+
Object.setPrototypeOf(this, RequestTimeoutError.prototype);
21+
}
22+
}

src/utils.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type { EngineName, EngineParameters } from "./types.ts";
22
import { version } from "../version.ts";
33
import https from "node:https";
44
import qs from "node:querystring";
5+
import { RequestTimeoutError } from "./errors.ts";
56

67
/**
78
* This `_internals` object is needed to support stubbing/spying of
@@ -103,7 +104,7 @@ export function execute(
103104
source: getSource(),
104105
});
105106
return new Promise((resolve, reject) => {
106-
https.get(url, { timeout }, (resp) => {
107+
const req = https.get(url, (resp) => {
107108
let data = "";
108109

109110
// A chunk of data has been recieved.
@@ -126,5 +127,12 @@ export function execute(
126127
}).on("error", (err) => {
127128
reject(err);
128129
});
130+
131+
if (timeout > 0) {
132+
setTimeout(() => {
133+
reject(new RequestTimeoutError());
134+
req.destroy();
135+
}, timeout);
136+
}
129137
});
130138
}

tests/utils_test.ts

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ import {
88
import { Stub, stub } from "https://deno.land/std@0.170.0/testing/mock.ts";
99
import {
1010
assertEquals,
11+
assertInstanceOf,
1112
assertMatch,
12-
assertRejects,
1313
} from "https://deno.land/std@0.170.0/testing/asserts.ts";
1414
import {
1515
_internals,
@@ -19,6 +19,7 @@ import {
1919
getSource,
2020
haveParametersChanged,
2121
} from "../src/utils.ts";
22+
import { RequestTimeoutError } from "../src/errors.ts";
2223

2324
loadSync({ export: true });
2425
const BASE_URL = Deno.env.get("ENV_TYPE") === "local"
@@ -230,9 +231,11 @@ describe("execute", {
230231
urlStub.restore();
231232
});
232233

233-
it("with short timeout", () => {
234-
assertRejects(async () =>
235-
await execute("/search", { q: "coffee", gl: "us" }, 1)
236-
);
234+
it("with short timeout", async () => {
235+
try {
236+
await execute("/search", { q: "coffee", gl: "us" }, 1);
237+
} catch (e) {
238+
assertInstanceOf(e, RequestTimeoutError);
239+
}
237240
});
238241
});

0 commit comments

Comments
 (0)