jacksonhoose / rxdb

:computer: :iphone: Client-Side Database for Browsers, NodeJS, electron, cordova, react-native and every other javascript-runtime :heavy_exclamation_mark:

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

RxDB

The reactive, serverless, client-side, offline-first database for your next javascript-application.



What is RxDB?

RxDB is a Javascript-based database with..

..these features.. ..for these platforms
  • Reactive (rxjs)

  • Replication / Sync

  • Schemas (jsonschema)

  • Mango-Query (MongoDB)

  • Encryption

  • Level-Adapters

  • Import/Export (.json)

  • MultiWindow-Support

  • Leader-Election

  • Key-Compression
      <img src="https://cdnjs.cloudflare.com/ajax/libs/browser-logos/39.2.2/chrome/chrome_24x24.png" title="Chrome" width="24px" />
      <img src="https://cdnjs.cloudflare.com/ajax/libs/browser-logos/39.2.2/firefox/firefox_24x24.png" title="Firefox" width="24px" />
      <img src="https://cdnjs.cloudflare.com/ajax/libs/browser-logos/39.2.2/safari/safari_24x24.png" title="Safari" width="24px" />
      <img src="https://cdnjs.cloudflare.com/ajax/libs/browser-logos/39.2.2/edge/edge_24x24.png" title="Edge" width="24px" />
      <img src="https://cdnjs.cloudflare.com/ajax/libs/browser-logos/39.2.2/archive/internet-explorer_9-11/internet-explorer_9-11_24x24.png" title="Internet Explorer 11" width="24px" />
      browsers
      <br /><br />
      <img src="docs/files/icons/nodejs.png" width="30px" />
      nodeJS
      <br /><br />
      <img src="docs/files/icons/angular.png" width="24px" />
      angular/ng2
      <br /><br />
      <img src="docs/files/icons/react.png" width="24px" />
      react
      <br /><br />
      <img src="docs/files/icons/react-native.png" width="24px" />
      react-native
      <br /><br />
      <img src="docs/files/icons/ionic.ico" width="24px" />
      ionic <br /><br />

      <img src="docs/files/icons/cordova.png" width="24px" />
      cordova / phonegap
     <br /><br />
      <img src="docs/files/icons/nativescript.png" width="24px" />
      nativescript
 <br /><br />
      <img src="docs/files/icons/electron.png" width="24px" />
      electron
       <br />
</td>



Menu

Quickstart

Installation:

npm install rxdb --save

ES6:

import * as RxDB from 'rxdb';
RxDB.create('heroesDB', 'websql', 'myLongAndStupidPassword', true)  // create database
  .then(db => db.collection('mycollection', mySchema))              // create collection
  .then(collection => collection.insert({name: 'Bob'}))             // insert document

ES5:

var RxDB = require('rxdb');
RxDB.create('heroesDB', 'websql', 'myLongAndStupidPassword', true)      // create database
  .then(function(db) {return db.collection('mycollection', mySchema);}) // create collection
  .then(function(collection) {collection.insert({name: 'Bob'});})       // insert document

Features

Mango-Query

To find data in your collection, you can use chained mango-queries, which you maybe know from mongoDB or mongoose. Example:

myCollection
  .find()
  .where('name').ne('Alice')
  .where('age').gt(18).lt(67)
  .limit(10)
  .sort('-age')
  .exec().then( docs => {
    console.dir(docs);
  });

Reactive

RxDB implements rxjs to make your data reactive. This makes it easy to always show the real-time database-state in the dom without manually re-submitting your queries.

heroCollection
  .find()
  .sort('name')
  .$ // <- returns observable of query
  .subscribe( docs => {
    myDomElement.innerHTML = docs
      .map(doc => '<li>' + doc.name + '</li>')
      .join();
  });

reactive.gif

MultiWindow/Tab - Support

When two instances of RxDB use the same storage-engine, their state and action-stream will be broadcasted. This means with two browser-windows the change of window #1 will automatically affect window #2. This works completely serverless.

multiwindow.gif

Replication

Because RxDB relies on glorious PouchDB, it is easy to replicate the data between devices and servers. And yes, the changeEvents are also synced.

sync.gif

Schema

Schemas are defined via jsonschema and are used to describe your data. Beside the jsonschema-keywords, you can also use primary and encrypted. Example:

var mySchema = {
    title: "hero schema",
    description: "describes a simple hero",
    type: "object",
    properties: {
        name: {
            type: "string",
            primary: true       // <- this means: unique, required, string and will be used as '_id'
        },
        secret: {
            type: "string",
            encrypted: true     // <- this means that the value of this field is stored encrypted
        },
        skills: {
            type: "array",
            maxItems: 5,
            uniqueItems: true,
            item: {
                type: "object",
                properties: {
                    name: {
                        type: "string"
                    },
                    damage: {
                        type: "number"
                    }
                }
            }
        }
    },
    required: ["color"]
};

Encryption

By setting a schema-field to encrypted: true, the value of this field will be stored in encryption-mode and can't be read without the password. Of course you can also encrypt nested objects. Example:

"secret": {
  "type": "string",
  "encrypted": true
}

Level-adapters

The underlaying pouchdb can use different adapters as storage engine. You can so use RxDB in different environments by just switching the adapter. For example you can use websql in the browser, localstorage in mobile-browsers and a leveldown-adapter in nodejs.

// this requires the localstorage-adapter
RxDB.plugin(require('rxdb-adapter-localstorage'));
// this creates a database with the localstorage-adapter
RxDB.create('heroesDB', 'localstorage');

Import / Export

RxDB lets you import and export the whole database or single collections into json-objects. This is helpful to trace bugs in your application or to move to a given state in your tests.

```js

// export a single collection myCollection.dump() .then(json => { console.dir(json); });

// export the whole database myDatabase.dump() .then(json => { console.dir(json); });

// import the dump to the collection emptyCollection.importDump(json) .then(() => { console.log('done'); });

// import the dump to the database emptyDatabase.importDump(json) .then(() => { console.log('done'); });


<h3>Leader-Election</h3>
<p>
  Imagine your website needs to get a piece of data from the server once every minute. To accomplish this task
  you create a websocket or pull-interval. If your user now opens the site in 5 tabs parallel, it will run the interval
  or create the socket 5 times. This is a waste of resources which can be solved by RxDB's LeaderElection.
</p>

```js
myRxDatabase.waitForLeadership()
  .then(() => {
      // this will only run when the instance becomes leader.
      mySocket = createWebSocket();
  });

In this example the leader is marked with the crown ♛

reactive.gif

Key-Compression

Depending on which adapter and in which environment you use RxDB, client-side storage is limited in some way or the other. To save disc-space, RxDB has an internal schema-based key-compression to minimize the size of saved documents.

Example:

// when you save an object with big keys
await myCollection.insert({
  firstName: 'foo'
  lastName:  'bar'
  stupidLongKey: 5
});

// RxDB will internally transform it to
{
  '|a': 'foo'
  '|b':  'bar'
  '|c': 5
}

// so instead of 46 chars, the compressed-version has only 28
// the compression works internally, so you can of course still access values via the original key.names
console.log(myDoc.firstName);
// 'foo'

Browser support

All major evergreen browsers and IE11 are supported. Tests automatically run against Firefox and Chrome, and manually in a VirtualBox for IE11 and Edge.

As RxDB heavily relies on PouchDB, see their browser support for more information. Also do keep in mind that different browsers have different storage limits, especially on mobile devices.

Getting started

Get started now by reading the docs or exploring the example-projects.

Contribute

[Check out how you can contribute to this project](./docs/Contribute.md).

Follow up

Follow me on [twitter](https://twitter.com/pubkeypubkey) to not miss the latest enhancements.

About

:computer: :iphone: Client-Side Database for Browsers, NodeJS, electron, cordova, react-native and every other javascript-runtime :heavy_exclamation_mark:

License:Apache License 2.0


Languages

Language:JavaScript 100.0%