@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.
107 lines • 3.44 kB
JavaScript
/**
* @module Cache
*/
import {} from "../../../../cache/contracts/_module.js";
import {} from "../../../../execution-context/contracts/_module.js";
import {} from "../../../../time-span/implementations/_module.js";
/**
* The `MemoryCacheAdapter` is used for easily faking{@link ICache | `ICache`} for testing.
*
* IMPORT_PATH: `"@daiso-tech/core/cache/memory-cache-adapter"`
* @group Adapters
*/
export class MemoryCacheAdapter {
map;
timeoutMap = new Map();
/**
* You can provide an optional {@link Map | `Map`}, that will be used for storing the data.
* @example
* ```ts
* import { MemoryCacheAdapter } from "@daiso-tech/core/cache/memory-cache-adapter";
*
* const map = new Map<any, any>();
* const cacheAdapter = new MemoryCacheAdapter(map);
* ```
*/
constructor(map = new Map()) {
this.map = map;
}
get(_context, key) {
return Promise.resolve(this.map.get(key) ?? null);
}
async getAndRemove(context, key) {
const value = await this.get(context, key);
await this.remove(key);
return value;
}
add(_context, key, value, ttl) {
const hasNotKey = !this.map.has(key);
if (hasNotKey) {
this.map.set(key, value);
}
if (hasNotKey && ttl !== null) {
this.timeoutMap.set(key, setTimeout(() => {
this.map.delete(key);
this.timeoutMap.delete(key);
}, ttl.toMilliseconds()));
}
return Promise.resolve(hasNotKey);
}
async put(context, key, value, ttl) {
const hasKey = await this.remove(key);
await this.add(context, key, value, ttl);
return hasKey;
}
update(_context, key, value) {
const hasKey = this.map.has(key);
if (hasKey) {
this.map.set(key, value);
}
return Promise.resolve(hasKey);
}
async increment(_context, key, value) {
const prevValue = this.map.get(key);
const hasKey = prevValue !== undefined;
if (hasKey) {
if (typeof prevValue !== "number") {
throw new TypeError(`Unable to increment or decrement none number type key "${key}"`);
}
const newValue = prevValue + value;
this.map.set(key, newValue);
}
return Promise.resolve(hasKey);
}
remove(key) {
clearTimeout(this.timeoutMap.get(key));
this.timeoutMap.delete(key);
return Promise.resolve(this.map.delete(key));
}
removeMany(_context, keys) {
let deleteCount = 0;
for (const key of keys) {
clearTimeout(this.timeoutMap.get(key));
this.timeoutMap.delete(key);
const hasDeleted = this.map.delete(key);
if (hasDeleted) {
deleteCount++;
}
}
return Promise.resolve(deleteCount > 0);
}
removeAll() {
this.map.clear();
this.timeoutMap.clear();
return Promise.resolve();
}
removeByKeyPrefix(_context, prefix) {
for (const key of this.map.keys()) {
if (key.startsWith(prefix)) {
clearTimeout(this.timeoutMap.get(key));
this.timeoutMap.delete(key);
this.map.delete(key);
}
}
return Promise.resolve();
}
}
//# sourceMappingURL=memory-cache-adapter.js.map