Skip to content

Commit

Permalink
prettified polling client and added final response error check
Browse files Browse the repository at this point in the history
  • Loading branch information
fern-bot committed Aug 13, 2024
1 parent eb0785f commit 06aedee
Showing 1 changed file with 25 additions and 28 deletions.
53 changes: 25 additions & 28 deletions src/PollingClient.ts
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -14,49 +14,46 @@ 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<any>;
Authorization: `Bearer ${options.apiKey}`,
},
})) as SuccessfulResponse<any>;

if (statusResponse.ok && statusResponse.body.status === "completed") {
return statusResponse;
} else if (statusResponse.ok && statusResponse.body.status === "failed") {
return {
ok: false,
error: {
reason: 'status-code',
body: statusResponse.body
}
reason: "status-code",
body: statusResponse.body,
},
} as FailedResponse<Fetcher.Error>;
} 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;
}
},
});
}
}

0 comments on commit 06aedee

Please sign in to comment.