Getting Started With DeltaDB

DeltaDB is an open source offline-first NoSQL database written in JavaScript. It is meant to be used in a front-end only design where the only backend needed is DeltaDB. The client writes to a local database and whenever the app is online it will sync with the database cloud.

Live Demos

Hello: a Hello World app for getting started with DeltaDB

The Code

Before we dive into the code, let’s try something fun. Open two browser windows and in both of them visit DeltaDB Hello. You’ll now be able to simulate two different users simultaneously using the app. In the first window type hola and then visit the second window. Do you see how hola is displayed in both windows? DeltaDB did this automatically by syncing with the cloud. You can even turn off your internet connection, enter another greeting and then turn your internet connection back on and DeltaDB will sync the greeting again. This app works both offline and online. Pretty cool, right?

Let’s go line by line through the code to see how everything works. We’ll be referring to the code at DeltaDB Hello.

Load DeltaDB

<script src="https://cdn.jsdelivr.net/deltadb/0.0.10/deltadb.min.js"></script>

The User Interface

<h1>DeltaDB says <input id="greeting-in" type="text"
onkeypress="onKeyPress(event)" />
</h1>

When the user presses enter, the onKeyPress function saves the greeting in the database. We’ll get to onKeyPress in a little bit.

We display the latest greeting:

<h3>DeltaDB says <em id="greeting-out"></em></h3>

Create the Database

var db = new DeltaDB('greetings-db',
'https://delta-dev.deltadb.io');

As soon as we create our database, it is ready to be used. If the database doesn’t exist then DeltaDB will automatically create it, assuming you are authorized.

Create a Collection

var greetings = db.col('greetings');

More serious apps have many types of documents so we use collections to keep all our docs organized.

Create the Document

var greeting = greetings.doc({ $id: 'greeting-id' });

Update the UI After the Doc is Loaded

greeting.on('load', function () {  document.getElementById('greeting-out').innerHTML =
greeting.get('text');
});

This code allows the app to display the latest greeting even when we are offline.

Update the UI When There are Remote Changes

greeting.on('attr:update', function (attr) {  document.getElementById('greeting-out').innerHTML = attr.value;});

Process Key Presses

function onKeyPress(e) {  if (e.keyCode === 13) { // pressed enter?    // save change
greeting.set({
text: document.getElementById('greeting-in').value });
// clear input box
document.getElementById('greeting-in').value = '';
}}

Congratulations!

Should DeltaDB be used in production?

What’s next?

DeltaDB on GitHub

Check out the DeltaDB API

A coder with a passion for JS, React, GraphQL, Docker and Serverless

A coder with a passion for JS, React, GraphQL, Docker and Serverless