From 7836c5a3db8229866ffa2216d80014c365cbdcee Mon Sep 17 00:00:00 2001 From: fern <126544928+fern-bot@users.noreply.github.com> Date: Wed, 14 Aug 2024 09:25:12 -0400 Subject: [PATCH] (feat): add Polling Client for Async APIs (#9) --- .fernignore | 2 ++ src/GooeyClient.ts | 60 ++++++++++++++++++++++++++++++++++++++++++++++ src/index.ts | 2 +- 3 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 src/GooeyClient.ts diff --git a/.fernignore b/.fernignore index 084a8eb..2d428e1 100644 --- a/.fernignore +++ b/.fernignore @@ -1 +1,3 @@ # Specify files that shouldn't be modified by Fern +src/GooeyClient.ts +src/index.ts \ No newline at end of file diff --git a/src/GooeyClient.ts b/src/GooeyClient.ts new file mode 100644 index 0000000..3ab06f5 --- /dev/null +++ b/src/GooeyClient.ts @@ -0,0 +1,60 @@ +import { GooeyClient as GooeyInternalClient } from "./Client"; +import { AsyncApiResponseModelV3 } from "./api"; +import { Fetcher, fetcher } from "./core"; +import { FailedResponse, SuccessfulResponse } from "./core/fetcher/APIResponse"; + +export class GooeyClient extends GooeyInternalClient { + constructor(options: GooeyInternalClient.Options) { + super({ + ...options, + fetcher: async (args: Fetcher.Args) => { + const response = await fetcher(args); + + if (response.ok) { + const location = response.headers?.get("Location") || response.body.statusUrl; + + if (location) { + const startTime = Date.now(); + + while (Date.now() - startTime < 30000) { + const statusResponse = (await fetcher<{ + status: "completed" | "failed"; + }>({ + url: location, + method: "GET", + headers: { + ...args.headers, + Authorization: `Bearer ${options.apiKey}`, + }, + })) as SuccessfulResponse; + + 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, + }, + } as FailedResponse; + } else if (!statusResponse.ok) { + return statusResponse; + } + } + + return { + ok: false, + error: { + reason: "timeout", + errorMessage: "async response timed out", + }, + }; + } + } + + return response; + }, + }); + } +} diff --git a/src/index.ts b/src/index.ts index 37bf9ca..922c858 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,4 @@ export * as Gooey from "./api"; -export { GooeyClient } from "./Client"; +export { GooeyClient } from './GooeyClient'; export { GooeyEnvironment } from "./environments"; export { GooeyError, GooeyTimeoutError } from "./errors";