lago-javascript-client
Version:
Lago JavaScript API Client
46 lines (45 loc) • 1.93 kB
JavaScript
// deno-lint-ignore-file no-explicit-any
import { Api } from "./openapi/client.js";
import { createRateLimitFetch } from "./rate_limit_fetch.js";
export const Client = (apiKey, apiConfig) => {
const { rateLimitRetry, ...restConfig } = apiConfig ?? {};
// Create rate-limit-aware fetch if configured
const customFetch = rateLimitRetry
? createRateLimitFetch((restConfig?.customFetch ?? globalThis.fetch), rateLimitRetry)
: restConfig?.customFetch;
const api = new Api({
securityWorker: (apiKey) => apiKey ? { headers: { Authorization: `Bearer ${apiKey}` } } : {},
// Cloudflare Workers doesn't support some options like credentials so need to override default
baseApiParams: {
redirect: "follow",
},
...restConfig,
...(customFetch && { customFetch }),
});
api.setSecurityData(apiKey);
return api;
};
// https://github.com/remix-run/remix/blob/ef26f7671a9619966a6cfa3c39e196d44fbf32cf/packages/remix-server-runtime/responses.ts#L60
function isResponse(value) {
return (value != null &&
typeof value.status === "number" &&
typeof value.statusText === "string" &&
typeof value.headers === "object" &&
typeof value.body !== "undefined");
}
export async function getLagoError(error) {
if (isResponse(error)) {
if (!error.bodyUsed) {
const errorJson = await error.json();
return errorJson;
}
return error.error;
}
throw new Error(error);
}
// Rate limit exports
export { LagoRateLimitError } from "./rate_limit_error.js";
export { parseRateLimitHeaders, parseRateLimitInfo, rateLimitUsagePct, } from "./rate_limit_headers.js";
export { createRateLimitFetch, } from "./rate_limit_fetch.js";
export { DEFAULT_RATE_LIMIT_THRESHOLDS, loggingRateLimitObserver, } from "./logging_rate_limit_observer.js";
export * from "./openapi/client.js";