• Stars
    star
    103
  • Rank 332,926 (Top 7 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 12 years ago
  • Updated about 8 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Warehouse.js is a data storage layer for node.js and browser providing unified API for many supported storage engines (MongoDB, MySQL, SQLite, in-memory and others).

Warehouse.js

Warehouse.js is a data storage layer for node.js and browser providing unified API for many supported storage engines (MongoDB, MySQL, SQLite, in-memory and others). You can create REST server or client with only few lines of code.

  • Supports multiple backends (MongoDB, MySQL, SQLite, in-memory and others)
  • Create REST server using few lines of code (compatible with Backbone.js)
  • Unified API for CRUD operations
  • Powerful query language RQL
  • MIT License

Make a quick protoype of your application without using an external database. Then switch to a robust storage (like MongoDB or MySQL) without the need to change your code.

Install

npm install warehousejs

REST server with express in node.js

var express = require('express'),
    warehouse = require('warehousejs'),
    MongoBackend = require('warehousejs/backend/mongodb');

var app = express.createServer(),
    store = new MongoBackend().objectStore('item');

warehouse.applyRoutes(app, store);

app.listen(80);

The example server above can be used with Backbone.js.

// client

var Model = Backbone.Model.extend({
   idAttribute: '_id' // Mongo uses _id for primary key
});

var items = new Backbone.Collection.extend({
   url: '/item',
   model: Model
});

items.fetch();

var john = items.create({name: 'John', age: 25});

john.set('age', 30);

john.save();

CRUD

The API is similar to IndexedDB API ( add, get, put, delete ). It is based on asynchronous promises (using Q library).

var jack = {id: 15, firstname: 'Jack', lastname: 'Hammer', age: 35};

// Create
store.add(jack)
     .then(function(result) { /* success */ })
     .fail(function(error) { /* error */ });

// Read
store.get(15)
     .then(function(result) { console.log(result.name) }); // outputs: Jack

// Update
jack.age = 40;
store.put(jack).then(callback);

// Delete
store.delete(15).then(callback);

// Delete all
store.clear().then(callback);

Querying

Queries are implemented using RQL.

// get items with id=15
store.query('id=15')
     .then(function(result) {}); // result is an Array

// get items with age >= 21
store.query('age=ge=21').then(callback);

// get items with price < 100, sort by acending price and descending rating
store.query('price=lt=100&sort(+price,-rating)').then(callback);

API

Backend

Backend represents DB that has collections for storing items. Common methods are:

  • objectStoreNames () - list collections or tables
  • objectStore(String name, [Object options]) - gets object store with specified name. If it does not exists then it is created.
  • createObjectStore (String name, [Object options]) - creates object store with specified name
  • deleteObjectStore (String name) - deletes object store with specified name (equivalent for droping table in SQL)
  • open () - opens database connection. You don't have to worry about it most of the times, because connection will be automatically opened first time when it is needed (lazy loading).
  • close () - closes database connection
  • isClosed () - is the connection closed?

Options for stores are:

  • keyPath - attribute that represents primary key (default 'id').

Store

Store represents collection of items (e.g. collection for MongoDB or table for SQL). Common methods are:

  • put (value, [key | directives])
  • add (value, [key | directives])
  • delete (key | directives)
  • get (key | directives)
  • clear ()
  • query (String query)

Key is a built-in type - String, Number, ... Directives is a object e.g. {key: '123'}

Common attributes:

  • String name
  • String keyPath

Backends

MongoDB

Backend for MongoDB using node-mongodb-native.

var options = {
    // default connection options
    host: 'localhost',
    port: 27017,
    database: 'default',

    // optional authentication credentials
    user: 'user',
    password: 'pass'
};

var MongoBackend = require('warehousejs/backend/mongodb'),
    backend = new MongoBackend(options),
    store = backend.objectStore('item');

You can use db and collection methods to get native driver objects.

store.db().then(function(db) {
    // native driver method
    db.ensureIndex('item', {price: 1}, function(err, result) {});
});

store.collection().then(function(collection) {
    // native collection method
    collection.find({tags: {$size: 2}}, function(err, result) {});
});

SQL

Backend for SQL databases, supports MySQL and SQLite. The underlying library node-persist also supports PostgreSQL and Oracle. However, those databases were not tested.

// options when using MySQL
var options = {
    driver: 'mysql',

    // default connection options
    host: 'localhost',
    port: 3306,
    name: 'default', // database name

    // optional authentication credentials
    user: 'user',
    password: 'pass'
};

// options when using SQLite
var options = {
    driver: 'sqlite3',
    filename: '/path/to/file.db',
};

var SqlBackend = require('warehousejs/backend/sql'),
    backend = new SqlBackend(options),
    store = backend.objectStore('item');

If you need to execute advanced queries, runSql and runSqlAll methods can be used.

// runSql(sql, values) - runs a sql statement that does not return results (INSERT, UPDATE, etc).
store.runSql("UPDATE people SET age = ?", [32])
     .then(function(status) {
         // people updated
     });

// runSqlAll(sql, values) - runs a sql statement that returns results (ie SELECT).
store.runSqlAll("SELECT * FROM people WHERE age = ?", [32])
     .then(function(items) {
         // items is an array containing all the people with age 32
     });

Filesystem

Backend which stores items as files on disk. This backend works only on server. Please note that querying speed will be slow for large amounts of data because no index is utilized.

It is useful for providing syncing capabilities in combination with Dropbox.

Pass path option to specify directory where the files will be stored. The path must exists.

var FsBackend = require('warehousejs/backend/fs'),
    backend = new FsBackend({path: '/path/to/storage'}),
    store = backend.objectStore('item');

ElasticSearch

Backend using ElasticSearch.

This backend works under both server and browser.

Pass url option to specify remote server address.

var ElasticSearchBackend = require('warehousejs/backend/elasticsearch'),
    backend = new ElasticSearchBackend({url: 'http://example.com/index'}),
    store = backend.objectStore('item');

NeDB

Backend for NeDB.

var NeBackend = require('warehousejs/backend/nedb'),
    backend = new NeBackend(),
    store = backend.objectStore('', options);

Be default the datastore is in-memory only. You can specify filename option for the persistent datastore.

store = backend.objectStore('', {filename: 'path/to/datafile'});

Popsat id?

Memory

Store items in memory using native Arrays and Objects. It is useful for making quick prototypes without the need of external dependencies.

This backend works under both server and browser.

Store takes optional argument json, which loads initial data into the datastore. Argument can be one of

  • Array
  • Object
  • Array JSON-encoded in String
  • Object JSON-encoded in String
  • String url of an remote resource, starts with 'http'

You can alternatively use fromJson and getJSON

var MemoryBackend = require('warehousejs/backend/memory'),
    backend = new MemoryBackend(),
    store, data;

// Array
data = [
  {id: 1, name: 'John'},
  {id: 2, name: 'Sarah'}
];

// Array in JSON
data = '[{"id":1,"name":"John"},{"id":2,"name":"Sarah"}]';

// Object
data = {
  1: {id: 1, name: 'John'},
  2: {id: 2, name: 'Sarah'}
};

// Object in JSON
data = {"1":{"id":1,"name":"John"},"2":{"id":2,"name":"Sarah"}};

// create the store with initial data
store = backend.objectStore('item', {json: data});

// create the store and set data later
store = backend.objectStore('item');
store.fromJSON(data);

REST

This backend is using remote REST server for storage. It is useful to access remote services.

If you combine it with a server (acting as a transparent proxy), you can basically use all implemented backends as if they were available for client.

This backend works under both server and browser.

Pass url option to specify remote server address (default is '/').

var RestBackend = require('warehousejs/backend/rest'),
    backend = new RestBackend({url: 'http://example.com'}),
    store = backend.objectStore('item');

Local Storage

Implements storage using W3C Web Storage (also known as DOM Storage or Local Storage).

Names of Object Stores have a special meaning:

  • session is a storage that is available for the duration of the page session
  • local is persistent (same-origin rules are applied}

This backend works only in browser.

var LocalBackend = require('warehousejs/backend/local'),
    backend = new LocalBackend();

// session only
var sessionStore = backend.objectStore('session');

// persistent
var localStore = backend.objectStore('local');

More Repositories

1

markmap

Visualize markdown documents as mindmaps
JavaScript
1,696
star
2

closh

Bash-like shell based on Clojure
Clojure
1,616
star
3

awesome-lisp-languages

A list of Lisp-flavored programming languages
712
star
4

liz

Lisp-flavored general-purpose programming language (based on Zig)
Clojure
261
star
5

GrammKit

Generate diagrams for parser grammars
JavaScript
235
star
6

lazy-lsp.nvim

Neovim plugin to auto install LSP servers
Lua
192
star
7

latinize

Simple library to convert accents (diacritics) from strings to latin characters.
JavaScript
148
star
8

atom-markdown-mindmap

Visualize markdown files as mindmaps in Atom editor
CoffeeScript
117
star
9

clojurescript-guide

My notes on ClojureScript
69
star
10

react-blessed-contrib

A wrapper for blessed-contrib widgets to be rendered with react-blessed.
JavaScript
61
star
11

notcurses-zig-example

Demo showing how to use Notcurses library for building terminal UIs with Zig
Zig
60
star
12

kmdoc

KMDoc is a software for an intelligent representation of knowledge useful for quick learning and browsing.
JavaScript
43
star
13

casio-f91w-fsm

Interactive model of the Casio F-91W watch using statecharts
Clojure
29
star
14

longdown

Convert longform markdown files to outline format used by Logseq
Clojure
28
star
15

parpar.nvim

Plugin for Neovim that seamlessly integrates Parinfer and Paredit for editing lisp code
Lua
27
star
16

dinodoc

Polyglot documentation system for building unified documentation sites
Clojure
27
star
17

osquery-rest-adapter

Visualize information about your OS (REST adapter for osquery compatible with Vega)
JavaScript
26
star
18

stratify

Visualize structure and dependencies of Clojure codebases
Clojure
21
star
19

notcurses-clojure-example

Demo showing how to use Notcurses library for building terminal UIs with Clojure
C
16
star
20

humble-outliner

Clojure
13
star
21

bindem

A light-weight library providing Knockout-like two-way declarative data binding for Backbone.
JavaScript
13
star
22

knowledge-base

Notes on various subjects represented using KMDoc knowledge format
HTML
8
star
23

archieml-peg

Alternative parser for ArchieML in JavaScript using PEG (Parsing Expression Grammar)
JavaScript
8
star
24

dotfiles

Shell
7
star
25

git-sheet

Interactive page which presents most used git commands as a cheat sheet.
JavaScript
6
star
26

czech-stemmer

This is a port of stemmer for Czech language to Javascript, for both node.js and browser.
JavaScript
6
star
27

jquery-tagin

Simple jQuery Tag Input plugin with advanced features
JavaScript
5
star
28

userstyles

CSS
5
star
29

solid-cljs

Clojure
5
star
30

humble-graal

Compile HumbleUI apps with GraalVM
Clojure
5
star
31

recline-warehouse

code for integration of Recline.js with Warehouse.js and other various additions to Recline
JavaScript
4
star
32

intools

Clojure
4
star
33

github-comparison

Show comparison of github repos in a table with this simple javascript component.
JavaScript
4
star
34

testing-without-mocks-clojure

Clojure
4
star
35

daba

Clojure
3
star
36

MEB-Genetic-Algorithm

Genetic Algorithm implementation in javaScript solving Minimum Energy Broadcast Problem
JavaScript
2
star
37

whitescape.js

Library for escaping whitespace characters
JavaScript
2
star
38

QueryHammer

QueryHammer is a visual tool that helps you create queries interactively
JavaScript
2
star
39

adventofcode

Clojure
2
star
40

rama-clj-playground

Clojure
2
star
41

lumo-unpack-binding

Unpack binary node bindings for apps bundled with pkg-lumo
JavaScript
1
star
42

vmp

1
star
43

calculator-exercise

Clojure
1
star
44

cljs-stickies

Sticky notes demo app with Drag n Drop written in ClojureScript
Clojure
1
star
45

notemx

NoteMX is a note taking app for Android with Dropbox sync using React Native
JavaScript
1
star
46

livereloader

[Deprecated] Simple HTTP server with livereload functionality. No setup, other apps or browser extensions required.
JavaScript
1
star
47

x11-playground

JavaScript
1
star
48

cljs-kanban

Kanban board with drag and drop written in ClojureScript
Clojure
1
star
49

commandray

CommandRay is a graphical command-line tool to discover and execute commands more efficiently
JavaScript
1
star
50

cljs-date-format-tool

A simple tool that helps creating date format strings
Clojure
1
star
51

pickfile

JavaScript file picker component supporting drag and drop, file chooser and remote URL
JavaScript
1
star