flamesshield-sdk
Version:
Flames Shield Smart rate limiting for Firebase Cloud Functions to protect your services from excessive requests
55 lines (54 loc) • 2.38 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RateLimiter = exports.QuotaCheckError = void 0;
class QuotaCheckError extends Error {
constructor(message) {
super(`Request rate limit error: ${message}`);
}
}
exports.QuotaCheckError = QuotaCheckError;
class RateLimiter {
constructor(
// a function that checks the current quota and updates it.
checkAndUpdateQuotaCall, logOptions = {}) {
this.checkAndUpdateQuotaCall = checkAndUpdateQuotaCall;
this.logOptions = logOptions;
}
/**
* Checks if the current usage is within the allowed quota and updates the quota.
*
*/
checkAndUpdateQuota() {
return __awaiter(this, void 0, void 0, function* () {
try {
if (this.logOptions.verbose) {
console.log('[FlameShield] Executing quota check and update');
}
const result = yield this.checkAndUpdateQuotaCall();
if (this.logOptions.verbose) {
console.log(`[FlameShield] Quota check result: ${result ? 'quota exceeded' : 'quota within limits'}`);
}
return result;
}
catch (error) {
if (this.logOptions.verbose) {
console.error('[FlameShield] Error during quota check:', error);
}
if (error instanceof Error) {
throw new QuotaCheckError(error.message);
}
throw new QuotaCheckError("Unknown error while checking and updating quota");
}
});
}
}
exports.RateLimiter = RateLimiter;