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.
Join the DZone community and get the full member experience.
Join For FreeIn 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?
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
Published at DZone with permission of Laura Czajkowski, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments