Last active
December 17, 2015 04:29
-
-
Save jed/5550980 to your computer and use it in GitHub Desktop.
an approach for incremental ids using levelup.
This file contains hidden or 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
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