@daiso-tech/core
Version:
The library offers flexible, framework-agnostic solutions for modern web applications, built on adaptable components that integrate seamlessly with popular frameworks like Next Js.
70 lines • 2.56 kB
JavaScript
/**
* @module RateLimiter
*/
import {} from "../../../../backoff-policies/contracts/_module.js";
import {} from "../../../../execution-context/contracts/_module.js";
import { RATE_LIMITER_STATE, } from "../../../../rate-limiter/contracts/_module.js";
import {} from "../../../../rate-limiter/implementations/adapters/database-rate-limiter-adapter/internal-rate-limiter-policy.js";
import {} from "../../../../utilities/_module.js";
/**
* @internal
*/
export class RateLimiterStorage {
adapter;
rateLimiterPolicy;
backoffPolicy;
constructor(settings) {
const { adapter, rateLimiterPolicy, backoffPolicy } = settings;
this.adapter = adapter;
this.rateLimiterPolicy = rateLimiterPolicy;
this.backoffPolicy = backoffPolicy;
}
static resolveStorageData(data) {
if (data === null) {
return null;
}
if (data.expiration <= new Date()) {
return null;
}
return data.state;
}
toAdapterState(state) {
const currentDate = new Date();
return {
success: state.type === RATE_LIMITER_STATE.ALLOWED,
attempt: this.rateLimiterPolicy.getAttempts(state, currentDate),
resetTime: this.rateLimiterPolicy.getExpiration(state, {
backoffPolicy: this.backoffPolicy,
currentDate,
}),
};
}
async atomicUpdate(args) {
const currentDate = new Date();
const state = await this.adapter.transaction(args.context, async (trx) => {
let currentState = RateLimiterStorage.resolveStorageData(await trx.find(args.context, args.key));
if (currentState === null) {
currentState =
this.rateLimiterPolicy.initialState(currentDate);
}
const newState = args.update(currentState);
await trx.upsert(args.context, args.key, newState, this.rateLimiterPolicy.getExpiration(newState, {
backoffPolicy: this.backoffPolicy,
currentDate,
}));
return newState;
});
return this.toAdapterState(state);
}
async find(context, key) {
const state = RateLimiterStorage.resolveStorageData(await this.adapter.find(context, key));
if (state === null) {
return null;
}
return this.toAdapterState(state);
}
async remove(context, key) {
await this.adapter.remove(context, key);
}
}
//# sourceMappingURL=rate-limiter-storage.js.map