UNPKG

@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.

94 lines 2.83 kB
/** * @module Lock */ /** * Note the `MemoryLockAdapter` is limited to single process usage and cannot be shared across multiple servers or different processes. * This adapter is meant to be used for testing. * * IMPORT_PATH: `"@daiso-tech/core/lock/adapters"` * @group Adapters */ export class MemoryLockAdapter { map; timeoutMap = new Map(); /** * @example * ```ts * import { MemoryLockAdapter } from "@daiso-tech/core/lock/adapters"; * * const lockAdapter = new MemoryLockAdapter(); * ``` * You can also provide an `Map`. * @example * ```ts * import { MemoryLockAdapter } from "@daiso-tech/core/lock/adapters"; * * const map = new Map<any, any>(); * const lockAdapter = new MemoryLockAdapter(map); * ``` */ constructor(map = new Map()) { this.map = map; } // eslint-disable-next-line @typescript-eslint/require-await async acquire(key, owner, ttl) { const hasNotKey = !this.map.has(key); if (hasNotKey) { this.map.set(key, { owner, expiration: ttl?.toEndDate() ?? null, }); } if (hasNotKey && ttl !== null) { this.timeoutMap.set(key, setTimeout(() => { this.map.delete(key); this.timeoutMap.delete(key); }, ttl.toMilliseconds())); } return hasNotKey; } // eslint-disable-next-line @typescript-eslint/require-await async release(key, owner) { const data = this.map.get(key); if (data === undefined) { return true; } if (data.owner !== owner) { return false; } clearTimeout(this.timeoutMap.get(key)); this.timeoutMap.delete(key); this.map.delete(key); return true; } // eslint-disable-next-line @typescript-eslint/require-await async forceRelease(key) { clearTimeout(this.timeoutMap.get(key)); this.timeoutMap.delete(key); this.map.delete(key); } // eslint-disable-next-line @typescript-eslint/require-await async refresh(key, owner, time) { const data = this.map.get(key); if (data === undefined) { return true; } if (data.owner !== owner) { return false; } if (data.expiration === null) { return true; } this.map.set(key, { ...data, expiration: time.toEndDate(), }); clearTimeout(this.timeoutMap.get(key)); this.timeoutMap.set(key, setTimeout(() => { this.timeoutMap.delete(key); this.map.delete(key); }, time.toMilliseconds())); return true; } } //# sourceMappingURL=memory-lock-adapter.js.map