diff --git a/modules/openapi-generator/src/main/resources/typescript/http/http.mustache b/modules/openapi-generator/src/main/resources/typescript/http/http.mustache index 440022a3e668..5581afbae0b0 100644 --- a/modules/openapi-generator/src/main/resources/typescript/http/http.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/http/http.mustache @@ -103,6 +103,7 @@ export class RequestContext { private body: RequestBody = undefined; private url: URL; private signal: AbortSignal | undefined = undefined; + private timeout?: number; {{#platforms}} {{#node}} private dispatcher: Dispatcher | undefined = undefined; @@ -170,6 +171,13 @@ export class RequestContext { this.url.searchParams.append(name, value); } + public setTimeout(timeout: number) { + this.timeout = timeout; + } + + public getTimeout(): number | undefined { + return this.timeout; + } /** * Sets a cookie with the name and value. NO check for duplicate cookies is performed * diff --git a/modules/openapi-generator/src/main/resources/typescript/http/isomorphic-fetch.mustache b/modules/openapi-generator/src/main/resources/typescript/http/isomorphic-fetch.mustache index a4f779b937c4..f61508b0cab6 100644 --- a/modules/openapi-generator/src/main/resources/typescript/http/isomorphic-fetch.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/http/isomorphic-fetch.mustache @@ -9,13 +9,42 @@ import "whatwg-fetch"; {{/browser}} {{/platforms}} +function withTimeout(fetchFn: any, timeout?: number) { + return (url: string, options: any = {}) => { + const controller = new AbortController(); + const userSignal = options.signal as AbortSignal | undefined; + + if (userSignal) { + if (userSignal.aborted) { + controller.abort(); + } else { + userSignal.addEventListener("abort", () => controller.abort()); + } + } + + let timeoutId: NodeJS.Timeout | undefined; + + if (timeout && timeout > 0) { + timeoutId = setTimeout(() => controller.abort(), timeout); + } + + return fetchFn(url, { ...options, signal: controller.signal }).finally( + () => { + if (timeoutId) clearTimeout(timeoutId); + } + ); + }; +} + + export class IsomorphicFetchHttpLibrary implements HttpLibrary { public send(request: RequestContext): Observable { let method = request.getHttpMethod().toString(); let body = request.getBody(); - const resultPromise = fetch(request.getUrl(), { + const effectiveFetch = withTimeout(fetch, request.getTimeout?.()); + const resultPromise = effectiveFetch(request.getUrl(), { method: method, body: body as any, headers: request.getHeaders(),