Skip to content

Commit

Permalink
locks: Add space.locks.getAll()
Browse files Browse the repository at this point in the history
Signed-off-by: Lewis Marshall <lewis.marshall@ably.com>
  • Loading branch information
lmars committed Aug 24, 2023
1 parent 4e605d2 commit e50c3fc
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
66 changes: 66 additions & 0 deletions src/Locks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,4 +341,70 @@ describe('Locks (mockClient)', () => {
expect(updateMsg.extras).not.toBeDefined();
});
});

describe('getAll', () => {
it<SpaceTestContext>('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}`);
}
}
});
});
});
14 changes: 14 additions & 0 deletions src/Locks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,20 @@ export default class Locks extends EventEmitter<LockEventMap> {
}
}

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<LockRequest> {
const self = await this.space.members.getSelf();
if (!self) {
Expand Down

0 comments on commit e50c3fc

Please sign in to comment.