npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mongodb-lock

v1.0.1

Published

Locks which uses MongoDB's atomic operations.

Downloads

972

Readme

mongodb-lock

Build Status NPM

A really light-weight way to get distributed locks with a nice API if you're already using MongoDB.

Version 1.0 !!!

Please note that the API has changed for v1.0 (compared to v0.4 and previously). This fits in with MongoDB Driver v3 and above.

Synopsis

Create a connection to your MongoDB database, and use it to create a lock object:

const mongodb = require('mongodb')
const mongoDbLock = require('.')

const url = 'mongodb://localhost:27017/'
const dbName = 'test'
const colName = 'locks'
const lockName = 'database-backup'

mongodb.MongoClient.connect(url, { useNewUrlParser: true }, function(err, client) {
  const db = client.db(dbName)
  const col = db.collection(colName)

  // supply the collection to use and the lock name
  const lock = mongoDbLock(col, lockName)
  lock.ensureIndexes(function(err, result) {
    console.log('Ensured Index:', err, result)
  })

  // Your Program Here!

})

Now, acquire the lock:

lock.acquire((err, code) => {
  if (err) {
    return console.error(err)
  }

  if ( !code ) {
    // lock was not acquired
    console.log('code=' + code)
    return
  }

  // lock was acquired
})

Once you have a lock, you have a 30 second timeout until the lock is released. You can release it earlier by supplying the code:

lock.release(code, (err, ok) => {
  if (err) {
    return console.error(err)
  }

  if (!ok) {
    console.log("Lock was not released, perhaps it's already been released or timed out")
    return
  }

  console.log('Lock released ok')
})

MongoDB Indexes

You should make sure any indexes have been added to the collection to make the queries faster:

lock.ensureIndexes(err => {
  if (err) {
    return console.error(err)
  }
  // all ok
})

Multiple Locks

Multiple locks can use the same collection and operate quite independently:

const dbBackupLock = mongoDbLock(db, 'locks', 'database-backup')
const hourlyStats = mongoDbLock(db, 'locks', 'hourly-stats')
const sendInvoices = mongoDbLock(db, 'locks', 'send-invoices')

Options

Currently there are two options: timeout and removeExpired

timeout

Currently the default is 30 seconds, but you can change it (in milliseconds):

// lock for 60 seconds
const opts = { timeout : 60 * 1000 }

// create the lock object
const uploadFiles = mongoDbLock(db, 'locks', 'upload-files', opts)

// acquire the lock
uploadFiles.lock((err, code) => {
  // locked for 60s
})

removeExpired

Currently the default value is false.

When set to true this will remove expired lock records from MongoDB instead of modifying them.

// remove old locks from MongoDB
const opts = { removeExpired : true }

// create the lock object
const cleanUpCacheDirs = mongoDbLock(db, 'locks', 'clean-up-cache-dirs', opts)

// all old locks are now deleted, rather than just hanging around

Changelog

1.0.0 (2019-08-08)

  • [FIX] made sure MongoDB Lock works with the MongoDB driver >v3
  • Yay - v1.0.0!

0.4.0 (2017-03-07)

  • Allow option so old locks are removed rather than updated (thanks Aiden Keating)

0.3.0 (2017-03-07)

  • Support for the MongoDB Driver v2 (thanks Aiden Keating)
  • Better ReadMe (thanks Marek)
  • Better ReadMe (thanks Krasiyan Nedelchev)

0.2.0 (2015-04-17)

  • [FIX] made sure that a 2nd .release() doesn't return ok (ie. it didn't do anything)

0.1.0 (2015-04-17)

  • [NEW] added ability to add indexes to MongoDB
  • [NEW] added lock()
  • [NEW] added release()

Author

$ npx chilts

   ╒════════════════════════════════════════════════════╕
   │                                                    │
   │   Andrew Chilton (Personal)                        │
   │   -------------------------                        │
   │                                                    │
   │          Email : [email protected]             │
   │            Web : https://chilts.org                │
   │        Twitter : https://twitter.com/andychilton   │
   │         GitHub : https://github.com/chilts         │
   │         GitLab : https://gitlab.org/chilts         │
   │                                                    │
   │   Apps Attic Ltd (My Company)                      │
   │   ---------------------------                      │
   │                                                    │
   │          Email : [email protected]              │
   │            Web : https://appsattic.com             │
   │        Twitter : https://twitter.com/AppsAttic     │
   │         GitLab : https://gitlab.com/appsattic      │
   │                                                    │
   │   Node.js / npm                                    │
   │   -------------                                    │
   │                                                    │
   │        Profile : https://www.npmjs.com/~chilts     │
   │           Card : $ npx chilts                      │
   │                                                    │
   ╘════════════════════════════════════════════════════╛

License

MIT - http://chilts.mit-license.org/2014/

(Ends)