Skip to content

Commit cead31b

Browse files
committed
Allow chaining the delay endpoint & fix delay calc bug
1 parent d5551c5 commit cead31b

File tree

3 files changed

+17
-6
lines changed

3 files changed

+17
-6
lines changed

src/endpoints/http-index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ export type HttpHandler = (
77
options: {
88
path: string;
99
query: URLSearchParams;
10+
handleRequest: (req: http.IncomingMessage, res: http.ServerResponse) => void;
1011
}
1112
) => MaybePromise<void>;
1213

src/endpoints/http/delay.ts

+14-5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { delay } from '@httptoolkit/util';
2-
import { HttpHandler, HttpEndpoint } from '../http-index.js';
2+
import { HttpHandler } from '../http-index.js';
33
import { buildHttpBinAnythingEndpoint } from '../../httpbin-compat.js';
44

55
const matchPath = (path: string) => path.startsWith('/delay/');
@@ -8,17 +8,26 @@ const defaultAnythingEndpoint = buildHttpBinAnythingEndpoint({
88
fieldFilter: ["url", "args", "form", "data", "origin", "headers", "files"]
99
});
1010

11-
const handle: HttpHandler = async (req, res, { path }) => {
12-
const delayMs = parseFloat(path.slice('/delay/'.length));
11+
const handle: HttpHandler = async (req, res, { path, handleRequest }) => {
12+
const followingSlashIndex = path.indexOf('/', '/delay/'.length);
13+
const followingUrl = followingSlashIndex !== -1 ? path.slice(followingSlashIndex) : '';
14+
const endOfDelay = followingSlashIndex === -1 ? path.length : followingSlashIndex;
15+
const delayMs = parseFloat(path.slice('/delay/'.length, endOfDelay));
1316

1417
if (isNaN(delayMs)) {
1518
res.writeHead(400);
1619
res.end('Invalid delay duration');
1720
}
1821

19-
await delay(Math.min(delayMs, 10 * 1000)); // 10s max
22+
await delay(Math.min(delayMs, 10) * 1000); // 10s max
2023

21-
return defaultAnythingEndpoint(req, res);
24+
if (followingUrl) {
25+
req.url = followingUrl;
26+
handleRequest(req, res);
27+
return;
28+
} else {
29+
return defaultAnythingEndpoint(req, res);
30+
}
2231
}
2332

2433
export const delayEndpoint = {

src/http-handler.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,8 @@ export function createHttpHandler(options: {
7575
console.log(`Request to ${path} matched endpoint ${matchingEndpoint.name}`);
7676
await matchingEndpoint.handle(req, res, {
7777
path,
78-
query: url.searchParams
78+
query: url.searchParams,
79+
handleRequest
7980
});
8081
} else {
8182
console.log(`Request to ${path} matched no endpoints`);

0 commit comments

Comments
 (0)