lago-javascript-client
Version:
Lago JavaScript API Client
48 lines (47 loc) • 1.69 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.loggingRateLimitObserver = exports.DEFAULT_RATE_LIMIT_THRESHOLDS = void 0;
const rate_limit_headers_js_1 = require("./rate_limit_headers.js");
/**
* Default usage thresholds (80%, 90%, 95%) at which the observer emits a log.
*/
exports.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() },
* });
* ```
*/
function loggingRateLimitObserver(options = {}) {
const thresholds = [...(options.thresholds ?? exports.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 = (0, rate_limit_headers_js_1.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;
}
}
};
}
exports.loggingRateLimitObserver = loggingRateLimitObserver;