Pre/Post hooks for leveldb
Intercept put/delete/batch operations on levelup.
Warning - Breaking Changes
The API for implementing pre hooks has changed.
Instead of mutating an array at once, the prehook
is called on each change hook(change, add)
and may call add(_change)
to add a new item into the batch.
Also, attaching hooks to leveldb is now simpler
var Hooks = require('level-hooks')
Hooks(db)
Example
var levelup = require('levelup')
var timestamp = require('monotonic-timestamp')
var hooks = require('level-hooks')
var db = levelup(file)
hooks(db)
db.hooks.pre({start: '', end: '~'}, function (change, add) {
add({type: 'put', key: '~log-'+timestamp()+'-'+change.type, value: change.key})
})
db.hooks.post(function (ch) {
})
Used by map-reduce
to make map-reduce durable across crashes!
Async Example
var levelup = require('levelup')
var timestamp = require('monotonic-timestamp')
var hooks = require('level-hooks')
var db = levelup(file)
hooks(db)
db.hooks.pre('counter!', function (op, done) {
db.get(op.key, function (err, val) {
op.value = Number(op.value || 0) + Number(val || 0)
cb()
})
})
db.put('counter!foo', 1, function (err) {
db.put('counter!foo', 2, function (err) {
db.get('counter!foo', console.log)
})
})
API
rm = db.hooks.pre (range?, hook(change, add(change, prefix?)))
If prefix
is a string
or object
that defines the range the pre-hook triggers on.
If prefix' is a string, then the hook only triggers on keys that _start_ with that string. If the hook is an object it must be of form
{start: START, end: END}`
hook
is a function, and will be called on each item in the batch
(if it was a put
or del
, it will be called on the change)
change
is always of the form {key: key, value: value, type:'put' | 'del'}
Pass additional changes to add
to add them to the batch.
If add is passed a string as the second argument it will prepend that prefix
to any keys you add.
To veto (remove) the current change call add(false)
.
db.hooks.pre
returns a function that will remove the hook when called.
rm = db.hooks.post (range?, hook)
Post hooks do not offer any chance to change the value.
but do take a range option, just like pre
db.hooks.post
returns a function that will remove the hook when called.
rm = db.hooks.async(range?, hook)
Async hooks are another kind of prehook that allow IO to happen
before the batch/put/del is processed.
Also, async hooked keys are processed strictly in series,
subsequent calls being queued until the previous call has returned.
This may be an issue for write heavy applications!
License
MIT