Skip to content

Commit

Permalink
feat(cache): add getLock
Browse files Browse the repository at this point in the history
  • Loading branch information
KABBOUCHI committed Nov 10, 2023
1 parent 5c8996b commit fd2a61c
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
8 changes: 6 additions & 2 deletions src/cache/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { memoryCacheDriver } from './drivers'

export interface ICacheLock {
acquire: () => Promise<boolean>|boolean
release: () => Promise<void>|void
acquire: () => Promise<boolean> | boolean
release: () => Promise<void> | void
}

export interface ICacheDriver {
Expand Down Expand Up @@ -126,4 +126,8 @@ export class Cache {
}
}
}

static async getLock (key: string, seconds: number, cb: () => Promise<void> | void) {
return await this.lock(key, seconds).get(cb)
}
}
8 changes: 8 additions & 0 deletions test/cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
})

0 comments on commit fd2a61c

Please sign in to comment.