Decorating a LevelUP database

Get familiar with the basics of LevelUp and LevelDB and learn how to implement a LevelUP plugin.

Before we start coding the next example, let’s say a few words about LevelUP, the module that we’re now going to work with.

Introducing LevelUP and LevelDB

LevelUP is a Node.js wrapper around Google’s LevelDB, a key-value store originally built to implement IndexedDB in the Chrome browser, but it’s much more than that. LevelDB has been defined as the “Node.js of databases” because of its minimalism and extensibility. Like Node.js, LevelDB provides blazingly fast performance and only the most basic set of features, allowing developers to build any kind of database on top of it.

The Node.js community, and in this case Rod Vagg, didn’t miss the chance to bring the power of this database into the Node.js world by creating LevelUP. Born as a wrapper for LevelDB, it then evolved to support several kinds of backends, from in-memory stores to other NoSQL databases such as Riak and Redis, to web storage engines such as IndexedDB and localStorage, allowing us to use the same API on both the server and the client, opening up some really interesting scenarios.

Today, there’s a vast ecosystem around LevelUP made of plugins and modules that extend the tiny core to implement features such as replication, secondary indexes, live updates, query engines, and more. Complete databases were also built on top of LevelUP, including CouchDB clones such as PouchDB, and even a graph database, LevelGraph, which can work both on Node.js and the browser!

Implementing a LevelUP plugin

In the next example, we’re going to see how we can create a simple plugin for LevelUP using the Decorator pattern, and in particular, the object augmentation technique, which is the simplest but also the most pragmatic and effective way to decorate objects with additional capabilities.

Note: For convenience, we’re going to use the level package, which bundles both levelup and the leveldown default adapter, which uses LevelDB as the backend.

What we want to build is a plugin for LevelUP that allows us to receive notifications every time an object with a certain pattern is saved into the database. For example, if we subscribe to a pattern such as {a: 1}, we want to receive a notification when objects such as {a: 1, b: 3} or {a: 1, c: 'x'} are saved into the database.

Let’s start to build our small plugin by creating a new level-subscribe.js named module. We’ll then insert the following code:

Get hands-on with 1200+ tech skills courses.