A simple key-value storage interface with adapters for different databases
Pirate provides a simple key-value storage interface with adapters for different storage systems. Pirate currently supports Redis and in-memory storage, with MongoDB and ElasticSearch adapters under development.
Important Pirate 1.0 is backwards incompatible with Pirate 0.9.x due to the change to an ES6-friendly Promise-based interfaces.
Here's a simple program to
get and object from Redis.
require "when/generator"consolerequire "pirate"adapter =port: 6379host: "127.0.0.1"book =key: "war-and-peace"title: "War and Peace"author: "Leo Tolstoy"published: "1969"call -># connect to the data storeyield adapterconnect# get a collectionbooks = yield adaptercollection "books"# store things in ityield booksput bookkeybook# get them back outassertdeepEqual yield booksget bookkeybook# update themyield bookspatch bookkeypublished: "1869"book.published = "1869"assertdeepEqual yield booksget bookkeybook
The elements of the interface are:
get keyReturns the object associated with the key or null.
put key, objectOverwrites the object associated with
object. Returns the updated object.
delete keyDeletes the object associated with
key. Returns nothing.
patch key, patchUpdates the object associated with
patch. Returns the updated object.
allReturns all the objects in the collection.
countReturns a count of all the objects in the collection.
All API methods return an Promise object.
The benefits of this approach are:
Simplify your code. The Pareto Principle often applies to storage systems, where you only need 20% of the features 80% of the time. Pirate optimizes that 80% while still allowing you to extend adapters to handle the other 20%, specific to your requirements.
Eliminate the impedance mismatch between HTTP and storage. Pirate follows a similar interface to that supported by HTTP:
delete. There's no equivalent to
postand there are a few additional methods, but semantically, they're very close.
Easily switch between storage implementations. Pirate's adapters not only hide the complexity of the underlying storage implementation, they make it much easier to change it. You can prototype using an in-memory solution, then use a database and later partition your data across servers.
Make use of promise-based interfaces. Node-style callbacks provide a reasonable least-common-denominator, but for more sophisticated applications, they can be tedious. Pirate uses promises to provide a generator-friendly interface, so you can just make your database calls using