A mutex node.js module who uses mongoose for locking
After searching in npm and realize that the only module for mutex with mongoose was depretated I decided to do one for myself.
The module it's very simple yet powerfull, it uses the uniq index for
_id and TTL index to prevent mutex to stay locked forever.
yarn add @chumager/mongoose-mutex
"use strict";const cluster = ;const Q = ;//If you play with one process then you don't need this...if clusterisMaster...Array10;elseconst Mutex = ;const db = ;db;
Avoid other process to take the resource for a while
"use strict";const cluster = ;const Q = ;const Mutex = ;const db = ;db;
I don't need a mutex (for now), what I needed was a way to avoid other processes to consume an API, but this way it'll help others developers...
the Mutex functions allows to define the mongoose model to use to lock.
|db||the mongoose instance to connect to and create the model.|
|model||"Mutex"||the model name.|
|collection||"__mutexes"||the collection name, remember to aavoit using an already existing collection.|
|clean||false||delete the collection after the Mutex model is created.|
|chainable||false||if true it chains the clean and then return the object with the lock function.|
|TTL||if the value exists then it creates the collection with a TTL index for expire field and then define expire as Date with a default of
In case of chainable options equals false, the it returns an object with the lock function, If it's true then returns a Promise with the same object.
the locking function.
|lockName||"mutex"||the name of the mutex, this allows you to use several mutex with the same collection.|
|fn||if defined then it's called after locking and chained with a final free call.|
|maxTries||1||how many tries before reject the locking, it's one because I needed that way, yo can define
|timeout||0||if greather than 0 then it fails if the time trying to lock it's above that, beware that this timeout is called after the locking process starts and in a local db service the process take about 25 ms, so values below that may not work.|
|delay||200||the time between tries. Remember not to use a low value to avoid over use of resources.|
if the fn options is given then it returns an error if can't lock or the result (rejectcion) of the fn. If no fn options is given then it returns a promise fullyfiled with the free function to release the lock, remember to use this function only after your code releases the resources needed.