From 4755787b69c75c3a69e3d48d01ce69a24570d3c7 Mon Sep 17 00:00:00 2001 From: dumbmoron Date: Wed, 11 Sep 2024 20:48:15 +0000 Subject: [PATCH] api-client: initial api request --- packages/api-client/src/api.ts | 45 ++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 packages/api-client/src/api.ts diff --git a/packages/api-client/src/api.ts b/packages/api-client/src/api.ts new file mode 100644 index 00000000..2e746963 --- /dev/null +++ b/packages/api-client/src/api.ts @@ -0,0 +1,45 @@ +import { CobaltResponseType, type CobaltAPIResponse } from "./types/response"; +import type { CobaltRequest } from "./types/request"; +import { CobaltReachabilityError } from "./types/errors"; + +export default class CobaltAPI { + #baseURL: string; + + constructor(baseURL: string) { + const url = new URL(baseURL); + + if (baseURL !== url.origin && baseURL !== `${url.origin}/`) { + throw new Error('Invalid cobalt instance URL'); + } + + this.#baseURL = url.origin; + } + + async request(data: CobaltRequest, headers: Record) { + const response: CobaltAPIResponse = await fetch(this.#baseURL, { + method: 'POST', + redirect: 'manual', + signal: AbortSignal.timeout(10000), + body: JSON.stringify(data), + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + ...headers + } + }) + .then(r => r.json()) + .catch((e) => { + const timedOut = e?.message?.includes("timed out"); + return { + status: CobaltResponseType.Error, + error: { + code: timedOut + ? CobaltReachabilityError.TimedOut + : CobaltReachabilityError.Unreachable + } + }; + }); + + return response; + } +};