diff --git a/README.md b/README.md index 6df3f29..fa34d54 100644 --- a/README.md +++ b/README.md @@ -255,6 +255,11 @@ const isLocked = await Cache.lock("key", 10).get(async () => { console.log("do something"); }); +// or +const isAcquired = await Cache.getLock("key", 10, async () => { + console.log("do something"); +}); + // or const lock = Cache.lock("key", 10); diff --git a/src/cache/index.ts b/src/cache/index.ts index 8238ad3..ef61d42 100644 --- a/src/cache/index.ts +++ b/src/cache/index.ts @@ -1,8 +1,8 @@ import { memoryCacheDriver } from './drivers' export interface ICacheLock { - acquire: () => Promise|boolean - release: () => Promise|void + acquire: () => Promise | boolean + release: () => Promise | void } export interface ICacheDriver { @@ -126,4 +126,8 @@ export class Cache { } } } + + static async getLock (key: string, seconds: number, cb: () => Promise | void) { + return await this.lock(key, seconds).get(cb) + } } diff --git a/test/cache.test.ts b/test/cache.test.ts index 24ad5b5..8fd4a5e 100644 --- a/test/cache.test.ts +++ b/test/cache.test.ts @@ -125,4 +125,12 @@ describe('cache', () => { expect(acquired).toBe(true) expect(notAcquired).toBe(false) }) + + test('atomic lock - getLock', async () => { + const acquired = await Cache.getLock('get-lock', 10, async () => { + await wait(1000) + }) + + expect(acquired).toBe(true) + }) })