Skip to content

Instantly share code, notes, and snippets.

@jed
Last active December 17, 2015 04:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jed/5550980 to your computer and use it in GitHub Desktop.
Save jed/5550980 to your computer and use it in GitHub Desktop.
an approach for incremental ids using levelup.
var levelup = require("levelup")
var path = __dirname + "db"
var options = {encoding: "json"}
var db = levelup(path, options)
function id(cb) {
if (typeof cb != "function") throw new TypeError
if (!id.queue) {
id.queue = []
setImmediate(run)
}
id.queue.push(cb)
}
function run() {
var cb = id.queue.shift()
if (!cb) return delete id.queue
db.get("last_id", function(err, id) {
if (err) {
if (err.name == "NotFoundError") id = 0
else return cb(err)
}
id++
db.put("last_id", id, function(err) {
if (err) cb(err)
else cb(null, id)
run()
})
})
}
module.exports = id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment