@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.
79 lines • 2.5 kB
JavaScript
/* eslint-disable @typescript-eslint/no-redundant-type-constituents */
/**
* @module Lock
*/
import {} from "../../../../lock/contracts/_module.js";
import {} from "../../../../time-span/implementations/_module.js";
/**
* @internal
*/
export class DatabaseLockAdapter {
adapter;
constructor(adapter) {
this.adapter = adapter;
}
async acquire(key, lockId, ttl) {
const expiration = ttl?.toEndDate() ?? null;
return await this.adapter.transaction(async (trx) => {
const lockData = await trx.find(key);
if (lockData === null) {
await trx.upsert(key, lockId, expiration);
return true;
}
if (lockData.owner === lockId) {
return true;
}
if (lockData.expiration === null) {
return false;
}
if (lockData.expiration <= new Date()) {
await trx.upsert(key, lockId, expiration);
return true;
}
return lockData.expiration <= new Date();
});
}
async release(key, lockId) {
const lockData = await this.adapter.removeIfOwner(key, lockId);
if (lockData === null) {
return false;
}
const { expiration } = lockData;
const hasNoExpiration = expiration === null;
if (hasNoExpiration) {
return true;
}
const { owner } = lockData;
const isNotExpired = expiration > new Date();
const isCurrentOwner = lockId === owner;
return isNotExpired && isCurrentOwner;
}
async forceRelease(key) {
const lockData = await this.adapter.remove(key);
if (lockData === null) {
return false;
}
if (lockData.expiration === null) {
return true;
}
return lockData.expiration > new Date();
}
async refresh(key, lockId, ttl) {
const updateCount = await this.adapter.updateExpiration(key, lockId, ttl.toEndDate());
return Number(updateCount) > 0;
}
async getState(key) {
const lockData = await this.adapter.find(key);
if (lockData === null) {
return null;
}
if (lockData.expiration === null) {
return lockData;
}
if (lockData.expiration <= new Date()) {
return null;
}
return lockData;
}
}
//# sourceMappingURL=database-lock-adapter.js.map