DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report

Creating Offline-First Apps With Couchbase Sync Gateway

You can use Couchbase and its Sync Gateway as a communication tool for your frontend and backend. That allows you to make an offline app that syncs at a given request.

Laura Czajkowski user avatar by
Laura Czajkowski
·
Apr. 05, 17 · Tutorial
Like (0)
Save
Tweet
Share
4.75K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, I’m going to propose an offline-first development using Couchbase as the communication tool between the backend and frontend.

While studying react-redux, something that I really liked is the Async Actions pattern where you have:

{ 
    type: 'FECH_POSTS_REQUEST' 
}

{ 
    type: 'FECH_POSTS_FAILURE', error: 'Oops' 
}

{ 
    type: 'FECH_POSTS_SUCCESS', response: 
    { 
        ... 
    } 
}


After understanding a bit more about Couchbase and Couchbase Sync Gateway, it seems possible to apply this kind of pattern and let Couchbase deal with all the communication of the app and having a fully functional offline app. This pattern provides a very good user experience because you actually render the page based on the current status of the app.

How Does It Work?

Image title

Application

The application itself never does any call to the backend. The only responsibility it has is to save states and render them. This way, it’s possible to have a fully functional app working offline.

Couchbase Lite/Sync Gateway

Couchbase Lite will be responsible for syncing the current state of the app to Couchbase Sync Gateway and retrieving new information once the document is updated in the backend.

Web Hooks

Once Couchbase Sync Gateway receives a document that matches the filter, it will do an HTTP call to the web app with the document it needs to update.

Web App

The Web App can do any kind of update like:

  • Creating a new task in a task queue
  • Retrieving data from an external API
  • Analyze some data/images (eg: OCR)

Hands On

To illustrate a bit how this concept works, I've developed a simple example where, once you save a specific document, the web application will dispatch a task that will get a random Star Wars character and update the document.

You can download all the code necessary to run an example of this solution.

The stack is composed by:

  • Web App – Flask
  • Task Queue – Celery + RabbitMQ
  • Sync Gateway (walrus mode)

To have it running, simple clone the git repo and run docker-compose:

git clone https://github.com/rafaelugolini/syncgateway_apiless_example

cd syncgateway_apiless_example

docker-compose up

Data Modeling

In this example, the key action is the primary source of the events. The document must be saved with:

{ "action": "person_request" }


To create a document curl, just use the following command

curl -H "Content-Type: application/json" -X POST -d '{"action":"person_request"}' http://localhost:4984/db/

Sync Gateway

In the configuration of the Sync Gateway, it's registered an event handler where for every document change with action == “person_request”, an API call will be made to the web app.

"event_handlers": {
    "document_changed": [
        {
            "handler": "webhook",
            "url": "http://web_service:5000/person_request/",
            "filter": `function(doc) {
                if (doc.action == "person_request") {
                    return true;
                }
                return false;
            }`
        }
    ]
}

Web App

The web app is a simple Flask API that receives a POST with the information of the document and dispatches a task to Celery.

The task will query a random Star Wars person from https://swapi.co/ and update the document:

{

    "action": "person_success",

    "gender": "female",

    "height": "168",

    "mass": "55",

    "name": "Zam Wesell"

}

 

Client

I developed a simple PouchDB client that will print all the documents from the Sync Gateway to the console. It basically runs this function every time there is a database change.

const getAllDocs = () => (
    db.allDocs({
        include_docs: true,
        attachments: true,
    }).then((result) => {
        console.log('\x1Bc'); // this clears the console
        console.log(util.inspect(result.rows, false, null));
    }).catch((err) => {
        console.log(err);
    })
);


You can get it from this Git repo.

yarn install
yarn start


app Sync (Unix) Web application Document

Published at DZone with permission of Laura Czajkowski, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • OpenVPN With Radius and Multi-Factor Authentication
  • What Are the Different Types of API Testing?
  • Journey to Event Driven, Part 1: Why Event-First Programming Changes Everything
  • Choosing the Right Framework for Your Project

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: