Previously in part one of this series
regarding Ionic Framework and Couchbase, I wrote about using Couchbase Lite to do local CRUD
(Create, Retrieve, Update, Delete) operations in a todo list example. This time around we’re going to take it to the next level and see
how to replicate changes across multiple devices and platforms using the Couchbase Sync Gateway.

The Prerequisites

In order to be successful in this tutorial, you need to have done the following:

  • Completed part one of the Ionic Framework blog series
  • Downloaded the Couchbase Sync Gateway
  • The Android SDK if building for Android
  • A Mac with Xcode installed if building for iOS

This tutorial is going to pick up exactly where part one of the series left off, so it is important that you had the first part in a working
state before continuing.

Configuring Couchbase Sync Gateway

In order to use Sync Gateway with our application we first need to create a configuration file. Create a file called
sync-gateway-config.json at the root of your project and include the following:

Don’t let the above overwhelm you as there isn’t too much going on. Most of the logic just checks to make sure documents have all the
required properties.

To highlight some of the main things happening here, first take a look at the databases.todos property.
This is going to be our remote database. The server we’re using is walrus which is a memory based solution bundled
into the Sync Gateway. It is good for testing before you’re ready to have it save into Couchbase Server. We are also choosing to enable
guest access, so registered users won’t be required for now.

This brings us into the sync JavaScript code. If the document is of type task, we check to see if a parent list id exists, otherwise we
force a fail. If it exists, then we save the document in the Sync Gateway prefixed with task- in the key. If the document
type is not a task, then it might be a list. Check to make sure the document has an owner property and save it to the
Sync Gateway prefixed with list- in the key.

Adding a New Ionic Route For Login

Adding to the AngularJS UI-Router

As of right now your AngularJS configuration should include two routes. One for the todo lists and one for tasks. What we want to do
now is include a third route for signing into the Sync Gateway. Inside your project’s www/js/app.js file, make the following
change:

Notice the new login state and that we changed our default route to be /login instead of /todoLists. The
route is good to go, we just need to create the view and controller to finalize it.

Creating a Login View

Inside your project’s www/templates directory, create a file called login.html and add the following code:

Sign in as a guest user

 

It is just a simple view with a button on it. When the user clicks the button, the basicLogin() function is called which
we’ll be creating in the login controller.

Creating a Login Controller

The controller for handling sign-ins will accomplish one very major task. It will start the replication process between the Sync Gateway
and the local device. Here is slim version of our controller that should be added to the www/js/app.js file:

Notice the $ionicHistory.nextViewOptions method. This is to prevent the hardware back button from taking users back
to the login screen after they’ve already logged in. More important for Android since iOS doesn’t have a hardware back.

Next you’ll see the $scope.basicLogin() function that was called from the UI view. Its contents will look like the following:

The first thing that happens is replication from the local device to the sync gateway. It is set to continuously replicate all changes. If
replication from local to remote starts successfully, the same happens for remote to local. Data will be continuously replicated from
the remote Sync Gateway down to the device.

If both are successful, the user will be redirected to the todo lists. Note that the Sync Gateway does not need to be operational to move
past login. If the server is not up, it will fail gracefully and still move on. Also note, that the IPs listed in the above function are
IPs that allowed me to communicate between simulator to the local host machine. They may differ for you and some research may need to be done.

Adding Owner Information To Document Data

Two minor changes need to be made to the way we store documents in the local database. In the $scope.insert of both
task and todo list controllers, an owner property must be added. In this case the owner will be guest.

The above code is an example of one of the $scope.insert functions. Again the only difference here is that we added an
owner property.

Testing Your Project

Running the Couchbase Sync Gateway

With the Sync Gateway downloaded, run the following from your Command Prompt or Terminal:

The Sync Gateway should start without issues.

Testing for Android

With a device connected or a simulator running, from the Command Prompt or Terminal, run the following two commands to
build and install the APK file:

Testing for iOS

There are two good ways to do this. You can either build the project and open it with Xcode, or you can build and emulate the application
without launching Xcode. The first can be done like so:

Then open the project’s platform/ios/ directory and launch the Xcode project file.

If you’ve installed the Node Package Manager (NPM) package ios-sim, you can do the following:

Conclusion

Using the Couchbase PhoneGap plugin and the Couchbase Sync Gateway, we’ve created a mobile todo list application that replicates data
locally and remotely so it can be accessed across multiple devices and platforms. We used AngularJS to easily connect to the RESTful endpoints
that Couchbase Lite exposes.

This series can be downloaded in full from the Couchbase Labs GitHub page.

Posted by Nic Raboy, Developer Advocate, Couchbase

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

46 Comments

  1. Is the sync between local and remote in real time?

  2. Hi Nic, Its a wonderful tutorial.. I have learnt a lot from your tutorials. Thanks for that. I have a doubt, i created app using your series of application part 1 and part 2 as base. I have done all the procedures you mentioned and I am able to connect to the couchbase sync gateway and i added some customers through my app . I am able to see the document in database too. But when i login with different customer in my mobile app, i am getting all the tickets generated by different customers in my mobile app.. Can you please help me is there any additional i have update to..

    1. Your sync gateway configuration would have to be more complex than what I listed to accommodate user authentication. Likewise you would have to make use of authentication on the local device:

      You might take a look at this and circle back:

      http://developer.couchbase.com

      I\’d be happy to answer your questions further 🙂

      1. Ya i got this. First i should not enter with the same customer on same device itself. I have to make a log out clear option if i want to login with different customer. But how to assign the channels individually for users to access.. Bcoz too much modifications in sync config file. I have tried even profile access also.. But failed.. Can you help me here for assigning channels for customers. Example:- As 2 customer and 2 employee\’s and admin.

        1. {
          \”log\”: [\”CRUD\”, \”REST+\”, \”Access\”],
          \”adminInterface\”:\”:4985\”,
          \”databases\”: {
          \”todos\”: {
          \”users\”: {
          \”GUEST\”: {\”disabled\”: true, \”admin_channels\”: [\”*\”]}
          },
          \”server\”: \”http://192.168.3.134:8091\”,
          \”sync\”:
          function (doc, oldDoc) {
          if (doc.type == \"ticket\") {
          channel(doc._id);
          var ownerName = doc.owner.substring(doc.owner.indexOf(\":\") + 1);
          console.log(doc.owner);
          console.log(doc._id);
          console.log(ownerName);
          access([doc.owner], doc._id);
          }
          }

          }
          }
          }

        2. James Nocentini October 12, 2015 at 3:24 pm

          You can dynamically create channels and grant access to them using the document properties.

          Data routing: http://developer.couchbase.com
          Data validation: http://developer.couchbase.com

          The access function takes the user\’s name as first parameter and channel name as the second parameter.
          If you have a document with the following schema:
          {
          \”_id\”: \”123\”,
          \”type\”: \”order\”,
          \”customer_id\”: \”ali\”
          }

          The Sync Function could contain the following:
          function(doc, oldDoc) {
          if (doc.type == \”order\”) {
          channel(doc._id);
          access(doc.customer_id, doc._id);
          }
          }
          Here you\’re saying \”insert the document in channel named 123 and give user ali access to channel 123\”.
          You can also use roles to assign users a particular role and grant a role access to a channel.

  3. Hi Nic, again – nice tutorial, I have been following this plus another couple from the couchbase forum too to complete a cloud based solution. I\’m able to get this solution up and running, quickly and easily thanks to your clear instructions. I have been looking at integrating the user auth in via facebook, there are numerous examples using lots of frameworks but non being ionic, do you know of any?

    1. Maybe take this sample app and integrate it with the Couchbase Sync Gateway APIs?:

      https://github.com/nraboy/ng-c

      1. Yep that\’s the one I used, I have this evening got something up and running. Where the problems came for me was in the sync gateway config json file. To get the sync up and running I have had to set cors to accept requests from * and I haven\’t got the sync section right yet, but I can see that the Facebook access token is being accepted and some documents are being synchronised. Some more reading to do this weekend, should have time over the next week to get the solution up and running correctly, any advice on suitable examples of the sync config or cors config in this instance would be very helpful

  4. Thanks for the tutorial Nic

    Will Couchbase Sync Gateway is work on local machine or it will require global server .

    1. You can prototype your app with Sync Gateway locally, but once you start using real devices you will have to use a remote server, otherwise they probably won\’t be able to connect to your machine.

  5. Hi Nic I follow your the tutorial ,I face the following problem when i insert data in Couch Base Server..

    1. I\’m not sure what this error means but you should always insert documents via the Sync Gateway REST API (http://developer.couchbase.com… otherwise the revision and access rules won\’t be created and it will mess up in the replication algorithm when you try to do a pull replication.

      1. My sync gateway is also not working properly when I test app no device
        I also access local system port globally 8091 in the same way i make 4984 and 4985 port to access globally but these port (4984,4985) not access globally.

  6. Hi Nic
    My sync gateway is also not working properly when I test app no device
    I also access local system port globally 8091 in the same way i make 4984 and 4985 port to access globally but these port (4984,4985) not access globally.

  7. Hi Nic,

    Thanks for tutorial now my sync gateway is working and data is replicate to server.

  8. Hi Nic,

    I am trying to implement login functionality with username and password using couchbase + ionic, Can you please point me to some tutorial..

      1. Hi Nic ,

        Thanks for the link its really help me.But if you can give some link of app which is on github and using login and signup functionality !!.

        1. There is currently no Ionic demo on GitHub for this. You can look at the PhoneGap version if you\’d like:

          https://github.com/couchbasela

          I think it would be more help to share what you\’ve tried and I can help you based on that.

          1. Hi Nic ,
            I want to update my \”task items\” in todo app can you please tell me the query to update the document ?

          2. You could call the updateDocument method:

            https://github.com/couchbasela

            updateDocument(documentId, documentRevision, jsonDocument);

          3. Hi Nic ,

            Thanks for the link .The updateDocument function is updating my local database Document(Mobile database) .
            But it is not pushing update to the server. Using sync gateway, CreateDocument and Delete function are working properly in my aplication and the Couchbase server sync is also working correctly through syncgateway. but while using update the server log is showing error as in screen shot

            Can you please help me on that ?

          4. Just so I\’m clear, the document does in fact get updated locally? It just doesn\’t replicate, correct?

            Best,

          5. I opened a ticket for you found here:

            https://github.com/couchbase/s

          6. Ravi can you post your sync function? (ideally post to a github gist or something that preserves the formatting)

          7. This conversation got moved here: https://forums.couchbase.com/t

          8. Hi Traun,
            I share the sync file on \”https://forums.couchbase.com/t…\” link as you said .
            I also used \”public channel\” in syncgateway file but i face same problem \”403 wrong user\”.
            Can you guide me on this problem or please point me to some tutorial.?

          9. Can you post that to the conversation on https://forums.couchbase.com/t… ?

          10. Hi Traun,

            I post my sync function on the link \”https://forums.couchbase.com/t…\” .
            I also used the \”public channel\” syncgateway file but i faced same problem \”403 wrong user\”.

            Can you guide me on this problem or please point me to some tutorial…

          11. Wellington Soares February 28, 2016 at 2:33 am

            Hello everybody and especially Nic, Congratulations on the good articles you have posted, I\’m exchanging CouchDB with Couchbase, however I can not do replication with username and password (HTTP method)

            What I have to do before replicate in basicLogin(user, pass)?

            todoDatabase.replicate (\”all\”, \”http://192.168.0.11:4984/todos\”, true) .then (function (result) {
            todoDatabase.replicate (\”http://192.168.0.11:4984/todos\”, \”all\”, true) .then (function (result) {

            sorry for my english.

            Tks!!!

          12. Hey @disqus_2gt0DNVITS:disqus,

            Since authentication is out of the scope of this article, can you please start a thread in the forums?

            https://forums.couchbase.com

            Best,

  9. Hi Nic,
    I am trying to implement Login and Sign up functionality with username and password using couchbaseLite + ionic , Can you please Guide me on this topic.

    1. Since login and sign up is out of the scope of this particular blog post, please bring your questions to the forums:

      https://forums.couchbase.com/

      Best,

  10. Hi Nick, I followed the instruction, code worked, but I still don\’t know how to sync db from Sync Gateway to app. I typed the sync_gateway url and the result is:
    {\”committed_update_seq\”:1,\”compact_running\”:false,\”db_name\”:\”todos\”,\”disk_format_version\”:0,\”instance_start_time\”:1463023463886566,\”purge_seq\”:0,\”state\”:\”Online\”,\”update_seq\”:1}. Look like it\’s an empty db.
    Could you tell me the instruction to create the records data in sync_gateway and sync to the app. Thanks.

    1. Something like this would start the sync process:

      You\’re never actually saving directly to sync gateway or couchbase server. You\’re saving locally and the changes are synced.

      Do you have any logs beyond what you shared with me?

      1. Thank for your reply, I change the url the log said that:
        Failed to load resource http://127.0.0.1:4984/todos/

        ERROR -> null app.js:86

        (anonymous function)

        Failed to load resource http://127.0.0.1:4984/_replicate

        1. What is the chunk of code around line 86?

  11. I keep getting error that address already in use. How to figure out which IP will work? I googled a lot, but couldn\’t find any solution.

    1. At what point are you getting this message? Are you getting it on the device? In the Terminal? In a web browser? The more information I have, the better I can help.

      Best,

      1. When I\’m running this command in the Terminal:
        /path/to/sync/gateway/bin/sync_gateway /path/to/project/sync-gateway-config.json

        1. If you don\’t properly stop it after you use it, the Sync Gateway service will still occupy the port. If this happens, you\’ll have to kill the process manually and this can vary depending on your operating system.

          Best,

          1. When I\’m running that command for the first time, I\’m getting the error: address already in use. And I ensured that I have no open ports from any other services.

            From the blog post: \”Also note, that the IPs listed in the above function are IPs that allowed me to communicate between simulator to the local host machine. They may differ for you and some research may need to be done.\”

            I don\’t get this line. I think I\’m missing something.

          2. Because I use Genymotion, I cannot connect to Sync Gateway from my simulators using localhost. That is why I have unique IP addresses. If Sync Gateway and Couchbase Server are running on the same machine, you will be using localhost.

            If you\’re having address conflicts, you may want to post in the forums as it doesn\’t seem related to this post.

            Best,

Leave a reply