Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / Node.js

Use of Realm Object in Realm Event Handler

5.00/5 (2 votes)
23 Jun 2018CPOL2 min read 5.3K  
Use of Realm object in Realm event handler

Before describing the deep concept of handling realm event handler changes, if you want to know about realm, then please go through these links this link and this link once.

Realm Platform

They provide a new standard in data synchronization. Realm helps companies build engaging mobile applications with minimal development time. The Realm Platform enables any development team, no matter the size, to include difficult-to-build features like two‑way data sync and realtime collaboration. Devote more time to what makes your app truly unique and less time to maintaining services.

Realm object database is a simple alternative to SQLite and Core Data and proudly open source.

I can just share the benefits of realm database quickly:

Screen Shot 2018-06-23 at 10.06.14 AM

Now Let’s Discuss About Handling Event Handler Changes

This is an important and awesome feature which you will not find in any other mobile DB like sqlite, Oracle Lite, Tiny DB, etc.

Once you setup realm database and connect to realm DB using Node JS, then for any changes in database, the event fires for that change and you can capture that event change in callback. If you have multiple databases or individual database for each user, then you can set the path to register the event change for those databases.

So for each operation (Insertion, Modification and Delete) in database, there will be event fired and in callback of that, you can do your operation in Node Js. For example, if there is data insertion in realm DB through mobile, then in Node Js server, you can catch the data and insert that data to MySql or move to AWS SQS or play with it.

A sample index.js file might look something like this. This example listens for changes to a user-specific private Realm at the virtual path /~/myuserDB. It will look for updated Coupon objects in these Realms, verify their coupon code if it wasn’t verified yet, and write the result of the verification into the isValid property of the Coupon object.

JavaScript
'use strict';
var Realm = require('realm'); 

// the URL to the Realm Object Server
var SERVER_URL = '//127.0.0.1:9080';

// The regular expression you provide restricts the observed Realm files to only the subset you
// are actually interested in. This is done in a separate step to avoid the cost
// of computing the fine-grained change set if it's not necessary.
var NOTIFIER_PATH = '^/([^/]+)/myUserDB$';

//declare admin user
let adminUser = undefined

// The handleChange callback is called for every observed Realm file whenever it
// has changes. It is called with a change event which contains the path, the Realm,
// a version of the Realm from before the change, and indexes indication all objects
// which were added, deleted, or modified in this change
var handleChange = async function (changeEvent) {
  // Extract the user ID from the virtual path, assuming that we're using
  // a filter which only subscribes us to updates of user-scoped Realms.
  var matches = changeEvent.path.match("^/([^/]+)/([^/]+)$");
  var userId = matches[1];

  var realm = changeEvent.realm;
  var coupons = realm.objects('Coupon');
  var couponIndexes = changeEvent.changes.Coupon.insertions;

  for (let couponIndex of couponIndexes) {
    var coupon = coupons[couponIndex];
    if (coupon.isValid !== undefined) {
      var isValid = verifyCouponForUser(coupon, userId);
      // Attention: Writes here will trigger a subsequent notification.
      // Take care that this doesn't cause infinite changes!
      realm.write(function() {
        coupon.isValid = isValid;
      });
    }
  }
}

function verifyCouponForUser(coupon, userId) {
    //logic for verifying a coupon's validity
}

// register the event handler callback
async function main() {
    adminUser = await Realm.Sync.User.login(`https:${SERVER_URL}`, 'realm-admin', '')
    Realm.Sync.addListener(`realms:${SERVER_URL}`, adminUser, NOTIFIER_PATH, 'change', handleChange);
}

main()

Note: In the above code, var realm = changeEvent.realm; where realm is the object which contains all rows, values which were changed in DB and other information as well. So in event handler file, there is no need to open realm to get realm object or to do any DB operation. You can use the above realm object throughout the event handler file carefully.

In the past, we made the same mistake when dealing with realm object. Like:

JavaScript
Realm.open({schema: [Car, Person]})
  .then(realm => {
    // ...use the realm instance here
  })
  .catch(error => {
    // Handle the error here if something went wrong
  });

So there is no need for you to open realm in Event handler file unless you need it. As you can see, the object realm is already available var realm = changeEvent.realm; globally.

For any DB operation like insertion, modification and delete operation, you can use the above realm object.

References

Hope you like the post and stay tuned for my next post about “deep analysis of handling event handler for each DB operation”.

Thanks for reading!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)