import { LockProviderFactory } from "@daiso-tech/core/lock";
import type { IDatabaseLockAdapter } from "@daiso-tech/core/lock/contracts";
import { MemoryLockAdapter, RedisLockAdapter, SqliteLockAdapter } from "@daiso-tech/core/lock/adapters";
import { Serde } from "@daiso-tech/core/serde";
import { SuperJsonSerdeAdapter } from "@daiso-tech/core/serde/adapters";
import { KeyPrefixer, type ISqliteDatabase, type AsyncFactoryFn } from "@daiso-tech/core/utilities";
import Redis from "ioredis"
import Sqlite from "better-sqlite3";
function lockAdapterFactory(database: ISqliteDatabase): AsyncFactoryFn<string, IDatabaseLockAdapter> {
return async (prefix) => {
const lockAdapter = new SqliteLockAdapter({
database,
tableName: `lock_${prefix}`
});
await lockAdapter.init();
return lockAdapter;
}
}
const database = new Sqlite("local.db");
const serde = new Serde(new SuperJsonSerdeAdapter());
const lockProviderFactory = new LockProviderFactory({
serde,
keyPrefixer: new KeyPrefixer("lock"),
adapters: {
sqlite: lockAdapterFactory(database),
memory: new MemoryLockAdapter(),
redis: new RedisLockAdapter({
client: new Redis("YOUR_REDIS_CONNECTION"),
serde,
}),
},
defaultAdapter: "memory",
});
import { LockProviderFactory } from "@daiso-tech/core/lock";
import type { IDatabaseLockAdapter } from "@daiso-tech/core/lock/contracts";
import { MemoryLockAdapter, RedisLockAdapter, SqliteLockAdapter } from "@daiso-tech/core/lock/adapters";
import { Serde } from "@daiso-tech/core/serde";
import { SuperJsonSerdeAdapter } from "@daiso-tech/core/serde/adapters";
import { KeyPrefixer, TimeSpan, type ISqliteDatabase, type AsyncFactoryFn } from "@daiso-tech/core/utilities";
import Redis from "ioredis"
import Sqlite from "better-sqlite3";
function lockAdapterFactory(database: ISqliteDatabase): AsyncFactoryFn<string, IDatabaseLockAdapter> {
return async (prefix) => {
const lockAdapter = new SqliteLockAdapter({
database,
tableName: `lock_${prefix}`
});
await lockAdapter.init();
return lockAdapter;
}
}
const database = new Sqlite("local.db");
const serde = new Serde(new SuperJsonSerdeAdapter());
const lockProviderFactory = new LockProviderFactory({
serde,
keyPrefixer: new KeyPrefixer("lock"),
adapters: {
sqlite: lockAdapterFactory(database),
memory: new MemoryLockAdapter(),
redis: new RedisLockAdapter({
client: new Redis("YOUR_REDIS_CONNECTION"),
serde,
}),
},
defaultAdapter: "memory",
});
// Will acquire key using the default adapter which is MemoryLockAdapter
await lockProviderFactory
.use()
.create("a")
.acquire();
// Will acquire key using the redis adapter which is RedisLockAdapter
await lockProviderFactory
.use("redis")
.create("a")
.acquire();
// You can change the default settings of the returned Lock instance.
await lockProviderFactory
.setDefaultTtl(TimeSpan.fromMinutes(2))
.use("sqlite")
.create("a")
.acquire();
The
LockProviderFactory
class is immutable.IMPORT_PATH:
"@daiso-tech/core/lock"