@node-idempotency/storage-adapter-memory
Version:
in memory storage adapter for node-idempotency
42 lines • 1.22 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MemoryStorageAdapter = void 0;
class MemoryStorageAdapter {
constructor() {
this.cache = new Map();
}
buildCacheValue(val, ttl) {
const v = {
item: val,
ttl,
};
if (ttl !== undefined && !isNaN(ttl)) {
const date = new Date();
date.setMilliseconds(date.getMilliseconds() + ttl);
v.ttl = date.getTime();
}
return v;
}
async setIfNotExists(key, val, { ttl } = {}) {
if (!this.cache.get(key)) {
this.cache.set(key, this.buildCacheValue(val, ttl));
return true;
}
return false;
}
async set(key, val, { ttl }) {
this.cache.set(key, this.buildCacheValue(val, ttl));
}
async get(key) {
const val = this.cache.get(key);
if (val?.ttl && !isNaN(val.ttl)) {
if (new Date() > new Date(val.ttl)) {
this.cache.delete(key);
return undefined;
}
}
return val?.item;
}
}
exports.MemoryStorageAdapter = MemoryStorageAdapter;
//# sourceMappingURL=adapter-memory.js.map