import endlessClient from "endless-client"; import { EndlessApiError, EndlessRequest, EndlessResponse, ClientConfig } from "./types"; import { VERSION } from "../version"; /** * Meaningful errors map */ const errors: Record = { 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 429: "Too Many Requests", 500: "Internal Server Error", 502: "Bad Gateway", 503: "Service Unavailable", }; /** * Given a url and method, sends the request with axios and * returns the response. */ async function request( url: string, method: "GET" | "POST", body?: Req, contentType?: string, params?: any, overrides?: ClientConfig, ): Promise { const headers: Record = { ...overrides?.HEADERS, "x-endless-client": `endless-ts-sdk/${VERSION}`, "content-type": contentType ?? "application/json", }; if (overrides?.TOKEN) { headers.Authorization = `Bearer ${overrides?.TOKEN}`; } /** * make a call using the @endless-labs/endless-client package * {@link https://www.npmjs.com/package/@endless-labs/endless-client} */ const response = await endlessClient({ url, method, body, params, headers, overrides }); return response; } /** * The main function to use when doing an API request. * * @param options EndlessRequest * @returns the response or EndlessApiError */ export async function endlessRequest(options: EndlessRequest): Promise> { const { url, endpoint, method, body, contentType, params, overrides } = options; const fullEndpoint = `${url}/${endpoint ?? ""}`; const response = await request(fullEndpoint, method, body, contentType, params, overrides); const result: EndlessResponse = { status: response.status, statusText: response.statusText!, data: response.data, headers: response.headers, config: response.config, url: fullEndpoint, }; if (result.status >= 200 && result.status < 300) { return result; } const errorMessage = errors[result.status]; throw new EndlessApiError(options, result, errorMessage ?? "Generic Error"); }