@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.
110 lines • 3.67 kB
JavaScript
/**
* @module Lock
*/
import { TimeSpan, } from "../../../../utilities/_module-exports.js";
/**
* @internal
*/
export class KyselyLockAdapter {
database;
expiredKeysRemovalInterval;
shouldRemoveExpiredKeys;
timeoutId;
constructor(settings) {
const { database, expiredKeysRemovalInterval = TimeSpan.fromMinutes(1), shouldRemoveExpiredKeys = true, } = settings;
this.expiredKeysRemovalInterval = expiredKeysRemovalInterval;
this.shouldRemoveExpiredKeys = shouldRemoveExpiredKeys;
this.database = database;
}
async deInit() {
await this.database.schema
.dropIndex("lock_expiresAt")
.ifExists()
.on("lock")
.execute();
await this.database.schema.dropTable("lock").ifExists().execute();
if (this.shouldRemoveExpiredKeys) {
clearTimeout(this.timeoutId);
}
}
async init() {
await this.database.schema
.createTable("lock")
.ifNotExists()
.addColumn("key", "varchar(255)", (col) => col.primaryKey())
.addColumn("owner", "varchar(255)")
.addColumn("expiresAt", "bigint")
.execute();
await this.database.schema
.createIndex("lock_expiresAt")
.ifNotExists()
.on("lock")
.columns(["expiresAt"])
.execute();
if (this.shouldRemoveExpiredKeys) {
this.timeoutId = setTimeout(() => {
void this.removeExpiredKeys();
}, this.expiredKeysRemovalInterval.toMilliseconds());
}
}
async removeExpiredKeys() {
await this.database
.deleteFrom("lock")
.where("lock.expiresAt", "<=", new Date().getTime())
.execute();
}
async insert(key, owner, expiration) {
await this.database
.insertInto("lock")
.values({
key,
owner,
expiresAt: expiration?.getTime() ?? null,
})
.execute();
}
async update(key, owner, expiration) {
const updateResult = await this.database
.updateTable("lock")
.where("lock.key", "=", key)
// Has expired
.where((eb) => eb.and([
eb("lock.expiresAt", "is not", null),
eb("lock.expiresAt", "<=", Date.now()),
]))
.set({ owner, expiresAt: expiration?.getTime() ?? null })
.executeTakeFirst();
return Number(updateResult.numUpdatedRows); // > 0;
}
async remove(key, owner) {
await this.database
.deleteFrom("lock")
.where("lock.key", "=", key)
.$if(owner !== null, (query) => query.where("lock.owner", "=", owner))
.execute();
}
async refresh(key, owner, expiration) {
const updateResult = await this.database
.updateTable("lock")
.where("lock.key", "=", key)
.where("lock.owner", "=", owner)
.set({ expiresAt: expiration.getTime() })
.executeTakeFirst();
return Number(updateResult.numUpdatedRows); // > 0;
}
async find(key) {
const row = await this.database
.selectFrom("lock")
.where("lock.key", "=", key)
.select(["lock.owner", "lock.expiresAt"])
.executeTakeFirst();
if (row === undefined) {
return null;
}
return {
expiration: row.expiresAt ? new Date(row.expiresAt) : null,
owner: row.owner,
};
}
}
//# sourceMappingURL=kysely-lock-adapter.js.map