@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.
83 lines • 3.1 kB
JavaScript
/**
* @module Lock
*/
import { TimeSpan, } from "../../../../utilities/_module-exports.js";
import { KyselyLockAdapter } from "../../../../lock/implementations/adapters/kysely-lock-adapter/_module.js";
import { Kysely, SqliteDialect } from "kysely";
import { KyselyTableNameTransformerPlugin } from "../../../../utilities/_module-exports.js";
/**
* To utilize the `SqliteLockAdapter`, you must install the `"better-sqlite3"` and `"@types/better-sqlite3"` packages.
*
* Note the `SqliteLockAdapter` is limited to single server usage and cannot be shared across multiple servers but it can be shared between different processes.
* To use it correctly, ensure all process instances access the same consistent, persisted database.
*
* IMPORT_PATH: `"@daiso-tech/core/lock/adapters"`
* @group Adapters
*/
export class SqliteLockAdapter {
databaseLockAdapter;
/**
* @example
* ```ts
* import { SqliteLockAdapter } from "@daiso-tech/core/lock/adapters";
* import Sqlite from "better-sqlite3";
*
* const database = new Sqlite("local.db");
* const lockAdapter = new SqliteLockAdapter({
* database,
* });
* // You need initialize the adapter once before using it.
* await lockAdapter.init();
* ```
*/
constructor(settings) {
const { database, tableName = "lock", shouldRemoveExpiredKeys = true, expiredKeysRemovalInterval = TimeSpan.fromMinutes(1), } = settings;
this.databaseLockAdapter = new KyselyLockAdapter({
database: new Kysely({
dialect: new SqliteDialect({
database: database,
}),
plugins: [
new KyselyTableNameTransformerPlugin({
lock: tableName,
}),
],
}),
expiredKeysRemovalInterval,
shouldRemoveExpiredKeys,
});
}
async removeExpiredKeys() {
await this.databaseLockAdapter.removeExpiredKeys();
}
/**
* Removes the table where the lock keys are stored and removes the table indexes.
* Note all lock data will be removed.
*/
async deInit() {
await this.databaseLockAdapter.deInit();
}
/**
* Creates the table where the lock keys are stored and it's related indexes.
* Note the `init` method needs to be called before using the adapter.
*/
async init() {
await this.databaseLockAdapter.init();
}
async insert(key, owner, expiration) {
await this.databaseLockAdapter.insert(key, owner, expiration);
}
async update(key, owner, expiration) {
return await this.databaseLockAdapter.update(key, owner, expiration);
}
async remove(key, owner) {
await this.databaseLockAdapter.remove(key, owner);
}
async refresh(key, owner, expiration) {
return await this.databaseLockAdapter.refresh(key, owner, expiration);
}
async find(key) {
return await this.databaseLockAdapter.find(key);
}
}
//# sourceMappingURL=sqlite-lock-adapter.js.map