The RxDB (short for Reactive Database) recommended in this issue is a NoSQL database for JavaScript applications, Such as websites, hybrid applications, electronic applications, progressive Web applications, and Node.js.
Reactive means that you can not only query the current state, but also subscribe to all state changes, such as query results or even individual fields of a document. This is useful for real-time UI-based applications because it is easy to develop and has huge performance benefits. To replicate data between client and server, RxDB provides modules for real-time replication, using any CouchDB-compliant endpoint as well as custom GraphQL endpoints.
RxDB feature
- Multi-platform support for browsers, nodejs, electron, cordova, react-native, and all other javascript-runtime
- Responsive data processing based on RxJS
- Offline priority keeps your app running when users don’t have Internet
- Replication between client and server data
- Schema-based json-schema Easy to learn standard
- Mango-Query is exactly what you know from mongoDB and mongoose
- Encrypt individual data fields to protect your user data
- Import/export of database state (json), ideal for encoding using TDD
- Multiple Windows to synchronize data between different browser Windows or nodejs processes
- ORM features to easily handle data code relationships and customize documents and collections
- Full TypeScript support for fast and secure coding (requires Typescript v3.8 or later)
Fast start
Install the RxDB library and RxJS (if not already installed)
npm install rxdb rxjs --save
Create a database using PouchDB RxStorage (you can also use other LokiJS or Dexie.js based storage).
import { createRxDatabase } from 'rxdb';
import { getRxStoragePouch, addPouchPlugin } from 'rxdb/plugins/pouchdb';
addPouchPlugin(require('pouchdb-adapter-idb'));
const myDatabase = await createRxDatabase({
name: 'heroesdb',
storage: getRxStoragePouch('idb')
});
Create schema for collection
const mySchema = {
title: 'human schema',
version: 0,
primaryKey: 'passportId',
type: 'object',
properties: {
passportId: {
type: 'string',
maxLength: 100 // <- the primary key must have set maxLength
},
firstName: {
type: 'string'
},
lastName: {
type: 'string'
},
age: {
description: 'age in years',
type: 'integer',
// number fields that are used in an index, must have set minium, maximum and multipleOf
minimum: 0,
maximum: 150,
multipleOf: 1
}
},
required: ['firstName', 'lastName', 'passportId'],
indexes: ['age']
}
Add collection to database
const myCollections = await myDatabase.addCollections({
humans: {
schema: mySchema
},
});
Insert document
const myDocument = await myDatabase.humans.insert({
passportId: 'foobar',
firstName: 'Alice',
lastName: 'Bobby',
age: 42
});
Subscription document value
myDocument.lastName$.subscribe(lastName => {
console.log('lastName is now ' + lastName);
});
Query some documents
const foundDocuments = await myDatabase.humans.find({
selector: {
age: {
$gt: 21
}
}
}).exec();
Subscription query result
myDatabase.humans.find({
selector: {
age: {
$gt: 21
}
}
}).$.subscribe(documents => {
console.log('query has found ' + documents.length + ' documents');
});
Update document
// either via atomicUpdate()
await myDocument.atomicUpdate(data => {
data.lastName = 'Carol';
return data;
});
// or via atomicPatch()
await myDocument.atomicPatch({
lastName: 'Carol'
});
Delete document
await myDocument.remove();
Development mode
The dev-mode plug-in adds a number of checks and validations to RxDB. This ensures that you are using the RxDB API correctly, so you should always use the development mode plug-in when using RxDB in development mode.
- Adds validation checks for schemas, queries, ORM methods, and document fields.
- Add a readable error message.
- Ensure that the readonlyJavaScript object does not mutate accidentally.
Important: The dev-mode plugin will increase your build size and decrease performance. It must always be used in development. You should never use it in production.
import { addRxPlugin } from 'rxdb';
import { RxDBDevModePlugin } from 'rxdb/plugins/dev-mode';
addRxPlugin(RxDBDevModePlugin);
Used with Node.js
async function createDb() {
if (process.env.NODE_ENV ! == "production") {
await import('rxdb/plugins/dev-mode').then(
module => addRxPlugin(module as any)
);
}
const db = createRxDatabase( /* ... */ );
}
Using with Angular
import { isDevMode } from '@angular/core';
async function createDb() {
if (isDevMode()){
await import('rxdb/plugins/dev-mode').then(
module => addRxPlugin(module as any)
);
}
const db = createRxDatabase( /* ... */ );
// ...
}
Pattern verification
RxDB has several plug-ins that you can use to ensure that your document data always matches the provided JSON schema.
Note: Schema validation may consume CPU resources and increase build size. You should always use scehma to validate plug-ins in development mode. For most use cases, you should not use validation plug-ins in production.
The validation module performs schema validation when you insert or update aRxDocument or copy document data using the replication plug-in. When validation plug-ins are not used, any document data can be protected, but undefined behavior may occur when data that does not conform to the schema is saved.
< Confirm
The lidate plug-in uses is-my-json-valid for schema validation.
import { addRxPlugin } from 'rxdb';
import { RxDBValidatePlugin } from 'rxdb/plugins/validate';
addRxPlugin(RxDBValidatePlugin);
ajv- verification
Another validation module that performs schema validation. This one uses ajv as the validator, which is faster. Better compliance with JSON Schema-Standard, but also with larger build sizes.
import { addRxPlugin } from 'rxdb';
import { RxDBAjvValidatePlugin } from 'rxdb/plugins/ajv-validate';
addRxPlugin(RxDBAjvValidatePlugin);
< p class = “PGC – h – arrow – right” data – track = “82” > < strong > validation – z – mode < / strong > < / p >
is-my-json-valid and ajv-validate are used to perform validations that may not be needed if eval() is not allowed in the content security policy. ‘unsafe-eval’ This uses z-schema as the validator instead of eval.
import { addRxPlugin } from 'rxdb';
import { RxDBValidateZSchemaPlugin } from 'rxdb/plugins/validate-z-schema';
addRxPlugin(RxDBValidateZSchemaPlugin);
data migration
With RxDB, you can provide a migration strategy for your collection that automatically (or on call) converts existing data from the old schema to the new. This ensures that the customer’s data always matches your latest code version.
< Add migration plug-in
To enable data migration, you must add the Migration plug-in.
import { addRxPlugin } from 'rxdb';
import { RxDBMigrationPlugin } from 'rxdb/plugins/migration';
addRxPlugin(RxDBMigrationPlugin);
< Provide policy
After creating a collection, you must provide migrationStrategies 0 when the schema’s version number is greater than. To do this, you must add an object to the property that migrationStrategies assigns a function to each schema version. The migrationStrategy is a function that takes the old document data as an argument and returns the new, transformed document data. If the policy returns null, the document will be deleted instead of migrated.
myDatabase.addCollections({
messages: {
schema: messageSchemaV1,
migrationStrategies: {
// 1 means, this transforms data from version 0 to version 1
1: function(oldDoc){
oldDoc.time = new Date(oldDoc.time).getTime(); // string to unix
return oldDoc;
}
}
}
});
Asynchronous strategies can also be used:
myDatabase.addCollections({
messages: {
schema: messageSchemaV1,
migrationStrategies: {
1: function(oldDoc){
oldDoc.time = new Date(oldDoc.time).getTime(); // string to unix
return oldDoc;
},
/**
* 2 means, this transforms data from version 1 to version 2
* this returns a promise which resolves with the new document-data
*/
2: function(oldDoc){
// in the new schema (version: 2) we defined 'senderCountry' as required field (string)
// so we must get the country of the message-sender from the server
const coordinates = oldDoc.coordinates;
return fetch('http://myserver.com/api/countryByCoordinates/'+coordinates+'/')
.then(response => {
const response = response.json();
oldDoc.senderCountry=response;
return oldDoc;
});
}
}
}
});
You can also filter the documents that should be migrated:
myDatabase.addCollections({
messages: {
schema: messageSchemaV1,
migrationStrategies: {
// 1 means, this transforms data from version 0 to version 1
1: function(oldDoc){
oldDoc.time = new Date(oldDoc.time).getTime(); // string to unix
return oldDoc;
},
/**
* this removes all documents older then 2017-02-12
* they will not appear in the new collection
*/
2: function(oldDoc){
if(oldDoc.time < 1486940585) return null;
else return oldDoc;
}
}
}
});
—END—
Open source protocol: Apache-2.0 license