Last active
August 28, 2022 15:31
-
-
Save kevcodez/796737bd2930d66a8082e7445664a585 to your computer and use it in GitHub Desktop.
Simple Distributed Lock with Mongo
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
async function acquireLock(name) { | |
// Open connection to database | |
const collection = await db.collection('locks'); | |
try { | |
// Insert an entry to the database, using the _id field, which already has a unique key constraint | |
await collection.insertOne({ _id: name }); | |
// No exception was thrown, so we successfully acquired a lock | |
return true; | |
} catch (ex) { | |
// 11000 means duplicate key error, which is expected on an active lock | |
if (ex.code !== 11000) { | |
// Uh-Oh, this is not an exception error | |
throw ex; | |
} | |
return false; | |
} | |
} | |
async function acquireAndExecute(name, fn) { | |
const locked = await acquireLock(name); | |
if (!locked) { | |
// Lock could not be acquired | |
return; | |
} | |
await fn(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment