diff --git a/src/Locks.test.ts b/src/Locks.test.ts index 7b33e2df..18d510b8 100644 --- a/src/Locks.test.ts +++ b/src/Locks.test.ts @@ -341,4 +341,70 @@ describe('Locks (mockClient)', () => { expect(updateMsg.extras).not.toBeDefined(); }); }); + + describe('getAll', () => { + it('returns all locks in the LOCKED state', async ({ space }) => { + await space.locks.processPresenceMessage( + Realtime.PresenceMessage.fromValues({ + action: 'update', + connectionId: '1', + extras: { + locks: [ + { + id: 'lock1', + status: 'pending', + timestamp: Date.now(), + }, + { + id: 'lock2', + status: 'pending', + timestamp: Date.now(), + }, + ], + }, + }), + ); + + await space.locks.processPresenceMessage( + Realtime.PresenceMessage.fromValues({ + action: 'update', + connectionId: '2', + extras: { + locks: [ + { + id: 'lock3', + status: 'pending', + timestamp: Date.now(), + }, + ], + }, + }), + ); + + const member1 = await space.members.getByConnectionId('1')!; + const member2 = await space.members.getByConnectionId('2')!; + const lock1 = space.locks.get('lock1'); + expect(lock1).toBeDefined(); + const lock2 = space.locks.get('lock2'); + expect(lock2).toBeDefined(); + const lock3 = space.locks.get('lock3'); + expect(lock3).toBeDefined(); + + const locks = space.locks.getAll(); + expect(locks.length).toEqual(3); + for (const lock of locks) { + switch (lock.request.id) { + case 'lock1': + case 'lock2': + expect(lock.member).toEqual(member1); + break; + case 'lock3': + expect(lock.member).toEqual(member2); + break; + default: + throw new Error(`unexpected lock id: ${lock.request.id}`); + } + } + }); + }); }); diff --git a/src/Locks.ts b/src/Locks.ts index c4637ad7..5c9b2492 100644 --- a/src/Locks.ts +++ b/src/Locks.ts @@ -52,6 +52,20 @@ export default class Locks extends EventEmitter { } } + getAll(): Lock[] { + const allLocks = []; + + for (const locks of this.locks.values()) { + for (const lock of locks.values()) { + if (lock.request.status === 'locked') { + allLocks.push(lock); + } + } + } + + return allLocks; + } + async acquire(id: string, opts?: LockOptions): Promise { const self = await this.space.members.getSelf(); if (!self) {