@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.
72 lines (71 loc) • 2.8 kB
TypeScript
/**
* @module Cache
*/
import { type ICacheAdapter } from "../../../../cache/contracts/_module-exports.js";
import type { ISerde } from "../../../../serde/contracts/_module-exports.js";
import type { IDeinitizable, IInitizable, TimeSpan } from "../../../../utilities/_module-exports.js";
import { type CollectionOptions, type Db } from "mongodb";
/**
*
* IMPORT_PATH: `"@daiso-tech/core/cache/adapters"`
* @group Adapters
*/
export type MongodbCacheAdapterSettings = {
database: Db;
serde: ISerde<string>;
collectionName?: string;
collectionSettings?: CollectionOptions;
};
/**
* To utilize the `MongodbCacheAdapter`, you must install the `"mongodb"` package and supply a {@link ISerde | `ISerde<string>`}, with an adapter like {@link SuperJsonSerdeAdapter | `SuperJsonSerdeAdapter `}.
*
* IMPORT_PATH: `"@daiso-tech/core/cache/adapters"`
* @group Adapters
*/
export declare class MongodbCacheAdapter<TType> implements ICacheAdapter<TType>, IInitizable, IDeinitizable {
private static filterUnexpiredKeys;
private static isMongodbIncrementError;
private readonly serde;
private readonly collection;
/**
* @example
* ```ts
* import { MongodbCacheAdapter } from "@daiso-tech/core/cache/adapters";
* import { Serde } from "@daiso-tech/core/serde";
* import { SuperJsonSerdeAdapter } from "@daiso-tech/core/serde/adapters"
* import { MongoClient } from "mongodb";
*
* const client = await MongoClient.connect("YOUR_MONGODB_CONNECTION_STRING");
* const database = client.db("database");
* const serde = new Serde(new SuperJsonSerdeAdapter());
* const cacheAdapter = new MongodbCacheAdapter({
* database,
* serde,
* });
* // You need initialize the adapter once before using it.
* await cacheAdapter.init();
* ```
*/
constructor(settings: MongodbCacheAdapterSettings);
/**
* Creates all related indexes.
* Note the `init` method needs to be called before using the adapter.
*/
init(): Promise<void>;
/**
* Removes the collection where the cache values are stored and all it's related indexes.
* Note all cache data will be removed.
*/
deInit(): Promise<void>;
private getDocValue;
get(key: string): Promise<TType | null>;
getAndRemove(key: string): Promise<TType | null>;
private isDocExpired;
add(key: string, value: TType, ttl: TimeSpan | null): Promise<boolean>;
put(key: string, value: TType, ttl: TimeSpan | null): Promise<boolean>;
update(key: string, value: TType): Promise<boolean>;
increment(key: string, value: number): Promise<boolean>;
removeMany(keys: string[]): Promise<boolean>;
removeAll(): Promise<void>;
removeByKeyPrefix(prefix: string): Promise<void>;
}