Home

Awesome

Overview

A reference implementation of a React Native Module for couchbase lite on iOS and Android.

⚠ NOTE: The plugin is not officially supported by Couchbase and there are no guarantees that the APIs exported by the module are up to date with the latest version of Couchbase Lite. The module implementation is available as an open source reference implementation for developers to use as a starting point and contribute as needed

React Native Modules allow mobile apps written in React Native to access native platform APIs. The sample module exports a relevant subset of native Couchbase Lite API functionality and makes it available to React native JS apps. You can extend this module to expose otherAPIs per module development guide.

LICENSE: The source code for the plugin is Apache-licensed, as specified in LICENSE. However, the usage of Couchbase Lite will be guided by the terms and conditions specified in Couchbase's Enterprise or Community License agreements respectively

Repo Folders

Sample App

An app that demonstrates core database, CRUD, query and sync functions of Couchbase Lite using the plugin is available here.

Exported APIs

The following is a list of APIs (and features) exported by the react-native plugin. See the description of Couchbase Lite Native API Specifications for an authoritative description of the API functionality.

NOTE: The plugin isn't a simple API passthrough. The plugin implements a Data Manager pattern and includes additional bookkeeping logic for managing and tracking open databases, replicators, listeners etc on behalf of the app. This avoids the need for the apps to implement all that bookkeeping logic. It is not required that you implement the plugin this way but it will simplify your app so you can focus on the apps UI and control logic. Also, by pushing these tasks into the plugin, app developers do not have to reimplement that logic for every app.

API methodsNative Class
CreateOrOpenDatabase (with specified Configuration)Database
closeDatabaseDatabase
deleteDatabaseDatabase
copyDatabaseDatabase
databaseExistsDatabase
addDatabaseChangeListenerDatabase
removeDatabaseChangeListenerDatabase
setDocument (With JSON OBJECT)MutableDocument
getDocumentMutableDocument
deleteDocumentMutableDocument
setBlobDatabase
getBlobDatabase
createValueIndexDatabase
createFTSIndexDatabase
deleteIndexDatabase
queryQuery
queryWithChangeListenerQuery
removeQueryChangeListenerQuery
enableConsoleLoggingDatabase
createReplicatorReplicator
replicatorStartReplicator
replicatorStopReplicator
replicationAddChangeListenerReplicator
replicationRemoveChangeListenerReplicator

Getting Started

We will look at the steps to integrate and use the react native module within a sample React Native app. The instructions assume some familiarity with React Native app development. You will do something similar when integrating into your own app.

iOS:

Android:

Usage

Here are a few examples of using the native module within your app

To use the module, you must declare the plugin at the on top of your app.js file.

import * as CBL from 'react-native-cblite';

Create Database

let config = {
    encryptionKey: "{{ENCRYPTION_KEY}}",
    directory: "{{DIRECTORY}}"
};

let dbName = '{{DATABASE_NAME}}'
CBL.CreateOrOpenDatabase(dbName,config, function(rs) { 
  console.log("database "+ dbName + " creation: "+ rs.toString())
  }, function(error) { 
    console.log(error.toString())
    });

Params

Example Response

Close Database

let response = CBL.closeDatabase(dbName,function(rs) { 
  console.log("database "+ dbName + " closing : "+ rs.toString())
  }, function(error) {
     console.log(error.toString())
     });

Params

Example Response

Delete Database

let response = CBL.deleteDatabase(dbName);
console.log("close" + dbName+ " database reponse is :" + response);

Params

Example Response

Database Exists


 var dbexists = CouchbaseNativeModule.databaseExists(dbName, dbConfig);
        

Params

Example Response

Create/Update Document

let docid = "{{DOCUMENT_ID}}";
let data = "{{JSON_OBJECT}}"; e.g { foo : 'bar', adam : 'eve' }
let dbName = "{{DATABASE_NAME}}";

CBL.setDocument(dbName,docid, JSON.stringify(data), function(rs) {
   console.log("Added document with body"+JSON.stringify(data) +" to db " + dbName + " "+ rs.toString())
   }, function(error) {
     console.log(error.toString()) 
     });

Params

Example Response

Get Document

let docid = "{{DOCUMENT_ID}}";
let dbName = "{{DATABASE_NAME}}";
CBL.getDocument(dbName,docid,function(rs) {
  console.log("Fetched document "+docid+ " from db " + dbName + " " + rs.toString()) 
  }, function(error) { 
    console.log(error.toString())
    });

Params

Example Response

Save Blob

var blobMeta = CBL.setBlob(dbName,contentType,blob);

Params

Example Response

Get Blob

CBL.getBlob(dbName,blobMeta,this.success_callback,this.error_callback);

Params

Example Response

Add Database Change Listener


var JSListenerEvent = 'OnDatabaseChanged'

var response = CBL.EventsListeners.addDatabaseChangeListener(dbName,JSListenerEvent);

if(response=='Success') {
    CBL.EventsListeners.addListener(JSListener, (eventResponse) => { console.log(eventResponse) });
    }
    else {
        console.log("ERROR: " + response);
    }


Params

Example Response for addChangeListener

Example Response in eventResponse

Remove Database Change Listener


var JSListenerEvent = 'OnDatabaseChanged'
.....

var response = CBL.removeDatabaseChangeListener(dbName);

if(response=='Success') {
     CBL.EventsListeners.removeAllListeners(JSListenerEvent);
     }
     else {
        console.log("ERROR: " + response);
     }

Params

Example Response

Create Value Index


let indexExpressions = ['name', 'location'];
let indexName = "nameLocationIndex";

 var response = CouchbaseNativeModule.createValueIndex(dbName, indexName, indexExpressions);
        

Params

Example Response

Create FTS Index


let indexExpressions = ['name', 'location'];
let indexName = "nameLocationIndex";
boolean ignoreAccents = true;
let language = "English";

 var response = CouchbaseNativeModule.createValueIndex(dbName, indexName, ignoreAccents, language, indexExpressions);
        

Params

Example Response

Delete Index


 let indexName = "nameLocationIndex";

 var response = CouchbaseNativeModule.deleteIndex(dbName, indexName);
        

Params

Example Response

Enable Logging

let domain = "REPLICATOR"; // e.g for ALL_DOMAINS enter null }
let logLevel = "verbose";
 
var response = await CouchbaseNativeModule.enableLogging(domain,logLevel);

Params

Example Response

Query


  let query = "{{QUERY_STRING}}"; //e.g "select * from users"

  CouchbaseNativeModule.query(dbName, query,function(rs) {
     console.log("Query result "+ rs.toString())
     }, function(error) { 
       console.log(error.toString())
       }););
        

Params

Example Response

Live Query


  let query = "{{QUERY_STRING}}"; //e.g "select * from users"
  let JSListenerEvent = "OnQueryChanged"

  let listenerAddResponse = await CouchbaseNativeModule.queryWithChangeListener(dbName, query, JSListenerEvent);

  if (listenerAddResponse == "Success") {
      CBL.EventsListeners.addListener(JsListener, function(response){
        conosole.log("Query Response : ", response);
      });  
  }


        

Params

Example Response

Example Response in eventResponse

Stop Live Query

  let query = "{{QUERY_STRING}}"; //e.g "select * from users"
  let JSListenerEvent = "OnQueryChanged"

  var stopQueryListener = await CouchbaseNativeModule.removeQueryChangeListener(dbname, query);

  if (stopQueryListener == "Success") {
      CBL.EventsListeners.removeAllListeners(stopQueryListener);
  }
        

Params

Example Response

Create Replicator

    var config = {
            databaseName: "{{DATABASE_NAME}}",
            target: "{{STRING_URI}}", // e.g "ws://10.0.2.2:4984/",
            authenticator: {
                authType: "{{AUTH_TYPE}}", // e.g. "Basic"
                username: "{{AUTH_USERNAME}}", // e.g. "user@example.com"
                password: "{{AUTH_PASSWORD}}" // e.g. "examplePassword"
            }, //optional
            continuous: {{BOOLEAN}}, //optional
            headers: [{HEADER_ARRAY}], //optional
            channels: [{CHANNELS_LIST}], //optional
            documentIds: [{DOCUMENT_ID_LIST}], //optional
            acceptOnlySelfSignedServerCertificate: {{BOOLEAN}}, //optional
            pinnedServerCertificateUri: {{STRING_URI}}, //optional
            heartbeat:{{HEARTBEAT_INT}}, //optional
          
        }

  let ReplicatorID = await CouchbaseNativeModule.createReplicator(dbname, config);
  
  console.log("ReplicatorID", ReplicatorID);

        

Params

Example Response

Start Replicator

  let startReplicatorResponse = await CouchbaseNativeModule.replicatorStart(dbname, ReplicatorID);
     
  console.log("Replicator Started", startReplicatorResponse)
        

Params

Example Response

Stop Replicator

  let stopReplicatorResponse = await CouchbaseNativeModule.replicatorStop(dbname, ReplicatorID);
     
  console.log("Replicator Stopped", stopReplicatorResponse)
    

Params

Example Response

Create Replicator Listener

  let JSListenerEvent = "OnReplicatorChanged"

  let ReplicatorListenerResponse = await CouchbaseNativeModule.replicationAddChangeListener(dbname, ReplicatorID, JSListenerEvent);
     
   if (ReplicatorListenerResponse == "Success") {
      CBL.EventsListeners.addListener(JSListenerEvent, function(response){
        conosole.log("Replicator Status Response : ", response);
      });  
  }
        

Params

Example Response

Example Response in eventResponse

Remove Replicator Listener

  let JSListenerEvent = "OnReplicatorChanged"

  var stopReplicatorListener = await CouchbaseNativeModule.replicationRemoveChangeListener(dbname, ReplicatorID);

  if (stopReplicatorListener == "Success") {
      CBL.EventsListeners.removeAllListeners(JSListenerEvent);
  }
        

Params

Example Response