Skip to content

Instantly share code, notes, and snippets.

@jchris
Last active May 4, 2018 04:29
Show Gist options
  • Save jchris/3c32524577deff3d69aa to your computer and use it in GitHub Desktop.
Save jchris/3c32524577deff3d69aa to your computer and use it in GitHub Desktop.
Couchbase Lite with React Native

Couchbase Lite with React Native

I went into this expecting a challenge but it was easy. Basically, Couchbase Lite has always had an optional HTTP listener that you can connect to from inside your app at http://lite.couchbase./mydatabase/. React Native has a fine XHR module and encourages using fetch so getting your app to sync can be as easy as adding some API calls to keep JSON in the database.

We haven't done a full example yet, but in the spirit of possiblity, here are quick instructions to connect Couchbase Lite iOS with a React Native app (generated from their cli).

#import "CouchbaseLite/CouchbaseLite.h"
#import "CouchbaseLiteListener/CBLListener.h"
#import "CBLRegisterJSViewCompiler.h"
  • Add a function to AppDelegate.m to launch Couchbase Lite
- (void)launchCouchbaseLite
{
  NSLog(@"Launching Couchbase Lite...");
  CBLManager* dbmgr = [CBLManager sharedInstance];
  CBLRegisterJSViewCompiler();
  NSLog(@"Couchbase Lite url = %@", dbmgr.internalURL);
}
  • Call this function from application didFinishLaunchingWithOptions:
[self launchCouchbaseLite];
  • Now in your JavaScript code you can create a new database with a PUT (here's a fancy version that does a GET first to check if the PUT is necessary):
var dbURL = "http://lite.couchbase./mydb/"
fetch(dbURL).then((response) => {
  if (response.status !== 200) {
    return fetch(dbURL, {method:"PUT"})
    .then((response) => response.json()).then((data) => {
      console.log("create db", data)
      return data;
    }).catch()
  }
})
  • You can create documents by POSTing to the database:
fetch(dbURL, {method:"POST", body : JSON.stringify({hello:"world"})})
.then((response) => response.json()).then((data) => {
  console.log("create document", data)
  return data;
}).catch()
  • And get all documents with a GET query:
fetch(dbURL + "_all_docs?include_docs=true")
.then((response) => response.json()).then((data) => {
  var docs = data.rows.map((row) => (row.doc));
  console.log("all documents", docs);
  return docs;
}).catch()

To see something like this in context, you could try my branch of marucc's demo app here.

@VonD
Copy link

VonD commented May 7, 2015

Hi Chris,
Many thanks for this very useful gist. I'm having trouble using couchbase lite attachments api : anytime I do a PUT to /docId/attachmentName, I get a 400 "Invalid attachment" response and I can't figure out why. A discussion on couchbase forum has not helped me find a solution to this issue. This also happens to me whith your ToDo App fork.
Do you have any idea why this might be ? Many thanks for your help,
Paul

@jchris
Copy link
Author

jchris commented Sep 22, 2015

@VonD I'm not sure... it's a deep stack with the http clients etc. Do you have code you can share, or maybe you posted it to the forum and you can link to the forum post?

@jchris
Copy link
Author

jchris commented Sep 22, 2015

@pennsong
Copy link

@jchris thanks for the post, I followed it, but could not use "http://lite.couchbase./mydb/" to connect the couchbase lite, details steps in below screenshots, any tips? thanks in advance(I'v debugged for a whole day:( ), the last two screenshot is a successful request FYI

  1. init the react native project named cbl4:

1

  1. init finished:

2

  1. open the ios project in cbl4:

3

  1. open the downloaded couchbase-lite-ios(I used the community version, but I've tried the enterprise version, the result is same):

4

  1. when drag and drop I always use it's options(manually check "Copy items if needed"):

5

  1. after the drag and drop the folder tree, drag and drop files are now under cbl4/cbl4/ (I've tried put these drag and drop files directly under cbl4/ or on a new created folder "Frameworks" cbl4/Frameworks, but the result is the same):

6

  1. -ObjC option is checked by default:

7

  1. before adding the dependencies:

8

  1. I drag libsqlite3.dylib and libz.dylib from /usr/lib to "Link Binary With Libraries":

9

  1. after adding the dependencies:

10

  1. added import and launchCouchbaseLite function:

11

  1. added [self launchCouchbaseLite]:

12

  1. fetch code:

13

  1. result:

14

  1. fetch code debug(using "http://www.baidu.com" to replace "http://lite.couchbase./mydb/"):

debug1

  1. debug result:

debug2

@pennsong
Copy link

@jchris I'v tested all react native github tags,
the latest tags can fellow your steps is 0.5.0(except replacing RCTWebSocketDebugger with WebSocket in App Root Folder /node_modules/react-native/Libraries/)
replacing steps:

  1. delete the RCTWebSocketDebugger
  2. then use step1 and step2 on follow https://facebook.github.io/react-native/docs/linking-libraries-ios.html#content

FYI

If you can figure out how to use the latest react-native with couchbase-lite, please let me konw, thanks in advance!

@pennsong
Copy link

solved: use the below method:

  • (void)launchCouchbaseLite
    {
    NSLog(@"Launching Couchbase Lite...");
    CBLManager* dbmgr = [CBLManager sharedInstance];
    CBLRegisterJSViewCompiler();

    CBLListener* listener = [[CBLListener alloc] initWithManager:dbmgr port:5800];
    [listener start:nil];

    NSLog(@"Couchbase Lite url = %@, and port %d", dbmgr.internalURL, listener.port);
    }
    then use "http://127.0.0.1:5800/yourDBName" as REST URL instead of "http://lite.couchbase./yourDBName"

@abuisman
Copy link

Thanks for the write-up and thanks @pennsong for the updated code it works just fine.

I had trouble creating a document with the following code (from above):

fetch(dbURL, {method:"POST", body : JSON.stringify({hello:"world"})})
      .then((response) => response.json()).then((data) => {
        console.log("create document", data)
        return data;
      }).catch()

I then had a look at the example app @jchris links to and I adjusted the code from this gist like so to get it working:

var id = 'some_cool_id';

fetch(dbURL  + id, {method:"PUT", body : JSON.stringify({hello:"world"})})
      .then((response) => response.json()).then((data) => {
        console.log("create document", data)
        return data;
      }).catch()

Note the method: 'PUT' instead of POST and the addition of an id in the url. It could be that I am missing something else that would have allowed me to POST without an id, but there you have it ;).

@atom992
Copy link

atom992 commented Oct 26, 2015

Is there a quick instructions to connect Couchbase Lite android with a React Native app?

@seigel
Copy link

seigel commented Dec 23, 2015

Any thoughts on replication?

@adamski
Copy link

adamski commented Jan 8, 2016

@atom992 it should be the same principle - employ the HTTP REST API interface of CouchbaseLite which is compatible with CouchDB, so (in theory) any request you can make to CouchDB you can make to Couchbase Lite by using the CouchbaseLiteListener class.
@seigel this also means you can trigger or set up any kind of replication, see http://developer.couchbase.com/documentation/mobile/1.1.0/develop/references/couchbase-lite/rest-api/server/post-replicate/index.html

@atvenu
Copy link

atvenu commented Mar 30, 2016

Thanks @adamski

@npomfret
Copy link

Did anyone solve the problem of not being able to access http://lite.couchbase./? I just get a network error. I've looked at some other examples out there like the cordova plugin, but can't see what they've done differently.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment