Created
August 17, 2021 16:50
-
-
Save murjam/adfd6d157b4effdf76999be56789410a to your computer and use it in GitHub Desktop.
Locking with redlock bunch of user IDs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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