lago-javascript-client
Version:
Lago JavaScript API Client
44 lines (43 loc) • 1.43 kB
JavaScript
import { rateLimitUsagePct } from "./rate_limit_headers.js";
/**
* Default usage thresholds (80%, 90%, 95%) at which the observer emits a log.
*/
export const DEFAULT_RATE_LIMIT_THRESHOLDS = [
0.8,
0.9,
0.95,
];
/**
* Returns a ready-to-use `onRateLimitInfo` callback that logs a warning each
* time rate limit usage crosses one of the configured thresholds.
*
* Example:
*
* ```ts
* import { Client } from "@getlago/lago-javascript-client";
* import { loggingRateLimitObserver } from "@getlago/lago-javascript-client";
*
* const client = Client(apiKey, {
* rateLimitRetry: { onRateLimitInfo: loggingRateLimitObserver() },
* });
* ```
*/
export function loggingRateLimitObserver(options = {}) {
const thresholds = [...(options.thresholds ?? DEFAULT_RATE_LIMIT_THRESHOLDS)]
.sort((a, b) => b - a); // descending
// deno-lint-ignore no-console
const log = options.log ?? ((m) => console.warn(m));
return function observe(info) {
const pct = rateLimitUsagePct(info);
if (pct === null)
return;
for (const threshold of thresholds) {
if (pct >= threshold) {
log(`Lago rate limit at ${(pct * 100).toFixed(0)}% (limit=${info.limit}, ` +
`remaining=${info.remaining}, reset=${info.reset}s, ` +
`${info.method} ${info.url})`);
return;
}
}
};
}