From 06aedee7026ea497d508041267c2cf73fed2ec90 Mon Sep 17 00:00:00 2001 From: fern-bot Date: Tue, 13 Aug 2024 16:29:24 -0400 Subject: [PATCH] prettified polling client and added final response error check --- src/PollingClient.ts | 53 +++++++++++++++++++++----------------------- 1 file changed, 25 insertions(+), 28 deletions(-) diff --git a/src/PollingClient.ts b/src/PollingClient.ts index 9471cab..8c205bb 100644 --- a/src/PollingClient.ts +++ b/src/PollingClient.ts @@ -1,7 +1,7 @@ -import { AsyncApiResponseModelV3 } from "api"; -import { GooeyClient } from "Client"; -import { Fetcher, fetcher } from "core"; -import { FailedResponse, SuccessfulResponse } from "core/fetcher/APIResponse"; +import { GooeyClient } from "."; +import { AsyncApiResponseModelV3 } from "./api"; +import { Fetcher, fetcher } from "./core"; +import { FailedResponse, SuccessfulResponse } from "./core/fetcher/APIResponse"; export class PollingClient extends GooeyClient { constructor(options: GooeyClient.Options) { @@ -14,21 +14,18 @@ export class PollingClient extends GooeyClient { const location = response.headers?.get("Location") || response.body.statusUrl; if (location) { - let polling = true; - new Promise(resolve => setTimeout(resolve, 15000)).then( () => { - polling = false; - }); + const startTime = Date.now(); - while (polling) { - const statusResponse = await fetcher<{ - status: "completed" | "failed" + while (Date.now() - startTime < 30000) { + const statusResponse = (await fetcher<{ + status: "completed" | "failed"; }>({ url: location, method: "GET", headers: { - Authorization: `Bearer ${options.apiKey}` - } - }) as SuccessfulResponse; + Authorization: `Bearer ${options.apiKey}`, + }, + })) as SuccessfulResponse; if (statusResponse.ok && statusResponse.body.status === "completed") { return statusResponse; @@ -36,27 +33,27 @@ export class PollingClient extends GooeyClient { return { ok: false, error: { - reason: 'status-code', - body: statusResponse.body - } + reason: "status-code", + body: statusResponse.body, + }, } as FailedResponse; + } else if (!statusResponse.ok) { + return statusResponse; } } - if (!polling) { - return { - ok: false, - error: { - reason: 'timeout', - errorMessage: 'async response timed out' - } - } - } - } + return { + ok: false, + error: { + reason: "timeout", + errorMessage: "async response timed out", + }, + }; + } } return response; - } + }, }); } }