Giter Club home page Giter Club logo

rnsync's Introduction

RNSync

npm version

About

RNSync is a React Native module that allows you to work with your Cloudant or CouchDB database locally (on the mobile device) and replicate to the remote database when needed.

RNSync is a wrapper for Cloudant Sync, which simplifies large-scale mobile development by enabling you to create a single database for every user; you simply replicate and sync the copy of this database in Cloudant with a local copy on their phone or tablet. This can reduce round-trip database requests with the server. If there’s no network connection, the app runs off the database on the device; when the network connection is restored, Cloudant re-syncs the device and server.

You can get an instance of Cloudant by creating an account on IBM Bluemix.

RNSync only supports ReactNative > 0.40

RNSync works with Redux Persist. Please read the RNSyncStorage doc for more info. You may also prefer the simplified API.

Installation

Install with npm

npm install --save rnsync

iOS

Add CDTDatastore to your Podfile

pod 'CDTDatastore'

Link and Pod install

react-native link rnsync
cd ios;pod install

Android

react-native link rnsync

Usage

Init

The below example exposes your credentials on every device, and the database must already exist, but it is fine for testing the package.

To avoid exposing credentials create a web service to authenticate users and set up databases for client devices. This web service needs to:

  • Handle sign in/sign up for users.
  • Create a new remote database for a new user.
  • Grant access to the new database for the new device (e.g., via API keys on Cloudant or the _users database in CouchDB).
  • Return the database URL and credentials to the device.

You can use the rnsync_key_generator package with your Express server to easily handle database and credentials creation. Also refer to cloudantApiKeyGenerator for an example of adding this functionality to your Express server if you do not wish to use rnsync_key_generator.

import rnsync from 'rnsync'

// init with your cloudant or couchDB database
var dbUrl = "https://user:pass@xxxxx"
var dbName = "name_xxxx"

rnsync.init(dbUrl, dbName, function(error)
{
  console.log(error)
});

Compact Store

This compacts the SQL database and disk storage by removing the bodies and attachments of obsolete revisions.

rnsync.compact(dbName)
  .catch(error => console.warn("Compaction error", error));

Delete Store

rnsync.deleteStore(dbName, function(error)
{
  console.log(error);
});

Read all documents

rnsync.readAll(dbName, (error, docs) => {
  if (error) {
    console.warn(error);
  } else {
    console.log(docs);
  }
})

Create

Both the object and the id are optional. If you leave out the object it will create a new doc that is empty. If you leave out the id that will be autogenerated for you.

var object = {x:10}
var id = "whatever"

rnsync.create(dbName, object, id, function(error, doc)
{
  console.log(doc.id)
});

rnsync.create(dbName, {name: 'jon'},  function(error, doc)
{
  console.log(doc.id)
});

// note: create will return an error if the id already exist
rnsync.create(dbName, 'user',  function(error, doc)
{
  console.log(doc.id)
});

Find or Create

Returns the doc with the specified id. It will create the doc if it does not already exist.

rnsync.findOrCreate(dbName, 'user',  function(error, doc)
{
  console.log(doc.id)
});

Retrieve

Returns the doc with the specified id.

var id = "whatever"

rnsync.retrieve(dbName, id, function(error, doc)
{
  console.log(JSON.stringify(doc.body))
});

Retrieve Attachments

Returns attachments for a doc with the specified ID, in the form:

{
  attachmentId: "base64encodedattachment"
}
rnsync.retrieveAttachments(dbName, id, function(error, attachments)
{
  console.log(attachments);
});

Update

When doing an update to a doc, you must include the revision.

doc.body.somechange = "hi mom"

rnsync.update(dbName, doc.id, doc.rev, doc.body, function(error, doc)
{
  console.log(JSON.stringify(doc.body))
});

Delete

rnsync.delete(dbName, doc.id, function(error)
{
  console.log(error)
});

Replicate

All of the CRUD functions only affect the local database. To push your changes to the remote server you must replicate. For more details see the replication docs

Push your local changes to the remote database

rnsync.replicatePush(dbName,  (error, msg, docs, batches) => console.log(error) );

Pull changes from the remote database to your local

rnsync.replicatePull(dbName,  (error, msg, docs, batches) => console.log(error) );

Do both a push and a pull

rnsync.replicateSync(dbName,  error => console.log(error) );

Note: Not currently implemented.

Find

Query for documents. For more details on the query semantics please see the Cloudant query documentation

var query = {name: 'John', age: { '$gt': 25 }}

rnsync.find(dbName, query, function(error, docs)
{
  console.log('found ' + docs.length)
});

Create Indexes

var indexes = {
  "TEXT":{"textNames":["Common_name","Botanical_name"]},
  "JSON":{"jsonNames":["Common_name","Botanical_name"]}
};

rnsync.createIndexes(dbName, indexes, function(error)
{
  console.log(error);
});

Events

The following events are emitted by this module:

  • rnsyncDatabaseOpened
  • rnsyncDatabaseClosed
  • rnsyncDatabaseCreated
  • rnsyncDatabaseDeleted
  • rnsyncDocumentCreated
  • rnsyncDocumentUpdated
  • rnsyncDocumentDeleted

These events may be handled as follows:

import { DeviceEventEmitter } from 'react-native';

this.docCreated = DeviceEventEmitter.addListener('rnsyncDocumentCreated', (e) => {
  console.log("doc created", e);
});

Usage with redux-persist

import { createStore } from 'redux'
import reducer from './redux/reducers/index'


import {persistStore, autoRehydrate} from 'redux-persist'
import rnsync, {RNSyncStorage} from 'rnsync'


let dbUrl = "https://xxx:xxx-bluemix.cloudant.com";
let dbName = "rnsync"

rnsync.init(dbUrl, dbName, error => console.log(error) )

const store = createStore(reducer, undefined, autoRehydrate())

persistStore(store, {storage: new RNSyncStorage(dbName)});

If you want to do replication before loading the store then:

rnsync.replicateSync(dbName).then(() => persistStore(store, {storage: new RNSyncStorage(dbName)}));

It is up to you to decide when and where to do replication. Later I will add the ability automatically do a replication push when data changes (from a whitelist you pass to rnsyncStorage.)

Author

Patrick Cremin, [email protected]

License

RNSync is available under the MIT license. See the LICENSE file for more info.

rnsync's People

Contributors

pwcremin avatar alexiri avatar thomwright avatar panos512 avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.