Skip to content

Instantly share code, notes, and snippets.

@murjam
Created August 17, 2021 16:50
Show Gist options
  • Save murjam/adfd6d157b4effdf76999be56789410a to your computer and use it in GitHub Desktop.
Save murjam/adfd6d157b4effdf76999be56789410a to your computer and use it in GitHub Desktop.
Locking with redlock bunch of user IDs
/**
* Creates a promise that resolves to either null when no lock was acquired or to user ID if lock was successful
* @param userId
* @returns {Function} async function (promise)
*/
const getLockPromise = (userId) => {
const lockKey = `send-notifications-lock:${userId}`;
return async () => {
try {
await redlock.acquireLock(lockKey, { retry: 0 });
return userId;
} catch (e) {
if (e instanceof CantLockRecordError) {
logger.debug(`Could not acquire lock for user ${userId}`);
} else {
logger.error(e);
}
return null;
}
};
};
/**
* Returns only the user IDs that the lock was acquired for
* @param userIds array
* @returns User IDs that were locked
*/
const lockUsersForNotifications = async (userIds) => {
const lockedUserIds = (await Promise.all(userIds.map(userId => getLockPromise(userId))))
.filter(userId => userId !== null);
return lockedUserIds;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment