@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.
78 lines (77 loc) • 2.94 kB
TypeScript
/**
* @module RateLimiter
*/
import { type CollectionOptions, type Db, type MongoClient, type ObjectId } from "mongodb";
import { type IRateLimiterData, type IRateLimiterStorageAdapter, type IRateLimiterStorageAdapterTransaction } from "../../../../rate-limiter/contracts/_module.js";
import { type ISerde } from "../../../../serde/contracts/serde.contract.js";
import { type IDeinitizable, type IInitizable, type InvokableFn } from "../../../../utilities/_module.js";
/**
* IMPORT_PATH: `"@daiso-tech/core/rate-limiter/mongodb-rate-limiter-storage-adapter"`
* @group Adapters
*/
export type MongodbRateLimiterStorageAdapterSettings = {
client: MongoClient;
database: Db;
/**
* @default "rateLimiter"
*/
collectionName?: string;
collectionSettings?: CollectionOptions;
serde: ISerde<string>;
};
/**
* IMPORT_PATH: `"@daiso-tech/core/rate-limiter/mongodb-rate-limiter-storage-adapter"`
* @group Adapters
*/
export type MongodbRateLimiterDocument = {
_id: ObjectId;
key: string;
state: string;
expiration: Date;
};
/**
* IMPORT_PATH: `"@daiso-tech/core/rate-limiter/mongodb-rate-limiter-storage-adapter"`
* @group Adapters
*/
export declare class MongodbRateLimiterStorageAdapter<TType> implements IRateLimiterStorageAdapter<TType>, IInitizable, IDeinitizable {
private readonly client;
private readonly collection;
private readonly serde;
/**
* @example
* ```ts
* import { MongodbRateLimiterStorageAdapter } from "@daiso-tech/core/rate-limiter/mongodb-rate-limiter-storage-adapter";
* import { MongoClient } from "mongodb";
* import { Serde } from "@daiso-tech/core/serde";
* import { SuperJsonSerdeAdapter } from "@daiso-tech/core/serde/super-json-serde-adapter"
*
* const client = await MongoClient.connect("YOUR_MONGODB_CONNECTION_STRING");
* const database = client.db("database");
* const serde = new Serde(new SuperJsonSerdeAdapter());
* const rateLimiterStorageAdapter = new MongodbRateLimiterStorageAdapter({
* client,
* database,
* serde
* });
* // You need initialize the adapter once before using it.
* await rateLimiterStorageAdapter.init()
* ```
*/
constructor(settings: MongodbRateLimiterStorageAdapterSettings);
/**
* Removes the collection where the rate limiter keys are stored and all it's related indexes.
* Note all rate limiter data will be removed.
*/
deInit(): Promise<void>;
/**
* Creates all related indexes.
* Note the `init` method needs to be called once before using the adapter.
*/
init(): Promise<void>;
private upsert;
transaction<TValue>(fn: InvokableFn<[
transaction: IRateLimiterStorageAdapterTransaction<TType>
], Promise<TValue>>): Promise<TValue>;
find(key: string): Promise<IRateLimiterData<TType> | null>;
remove(key: string): Promise<void>;
}