real m

Serverless Logic With Realm Functions

Final product image
What You’ll Be Creating

In the previous tutorials, we took a look at the Realm Platform as well as the on-device Realm Database for iOS. In that post, you learned how to synchronize your app data locally as well as in the cloud. While this presents a complete solution for many developers, you may want to do more than just persist data, but also run server-side logic. 

This year, Realm added the ability to create serverless functionality via Realm Functions, allowing developers to create program logic to respond to database events automatically.

Realm’s serverless computing solution is akin to Amazon’s AWS Lambda or Microsoft’s Azure Functions. Like them, it allows you to run code without having to provision your own servers. Your functions will run on Realm Object Server. Realm Functions provide the chance to write JavaScript-powered functions that react to Realm’s live objects and manage them through the Realm dashboard interface. 

Whether you need to react to live-objects and send a push notification to users or trigger an API call to another third-party vendor SDK like Twilio, reactive events via functions allow you to respond and react server-side. In this tutorial, you are going to learn how to work with Realm Functions.

Objectives of This Tutorial

In this tutorial, you’ll learn how to implement and work with Realm Functions to create a sample trigger function that will update a value in our cloud database. This will be a contrived example, but you can apply this knowledge to more practical problems. 

In this tutorial, we will be covering the following:

  • event handling and functions
  • reasons to use functions
  • creating functions from the dashboard
  • integrating functions into your Realm Object Server.

Assumed Knowledge

This tutorial assumes you’ve read through the previous two tutorials in this series. As Realm Functions are written in JavaScript, you should also have a basic understanding of that language, although you don’t need to be an expert. 

If you want a primer on Realm, check out the previous posts in this series.

  • iOS SDK
    Realm Mobile Database for iOS
    Doron Katz
  • Swift
    Getting Started With Realm Mobile Platform for iOS
    Doron Katz

What Are Realm Functions? 

In the previous tutorials you’ve used Realm to create on-device persistence, as well as synchronizing user data with the cloud, but one notable absence has been in the ability to work intelligently with data server-side. We sometimes need server-side logic that can respond to changes in the data, the same way triggers work in traditional databases. 

This is where Realm Functions come in, providing the ability to anticipate and react to changes in Realms. Realm Functions also empowered teams to create server-side logic without needing a dedicated back-end developer, building on top of the Realm Platform with minimal configuration, and without having to worry about serialization or adding additional endpoints to the server. 

Realm Functions is our “serverless” app logic layer, where you can easily build server-side features with simple JavaScript, no backend team required. When synced data changes, your custom logic executes—making it fast and easy for mobile developers to build and ship sophisticated server-dependent features. — Realm.io

Event Handling in Realm

Functions handle events through the Realm Object Server with Node.js functions which are subsequently called by the Realm Object Server global listening API, which passes changeEvent() objects triggered via the function logic. This is accomplished through the server-side Node.js instance, which connects to the global event listener API, allowing developers to observe for changes across Realms and filtering for specific Realms that match a specific Regex pattern. 

Developers can therefore listen to specific and unique Realm paths which may be set up for specific users, and then react to those user’s changes. The global event listener then triggers a notification for the server-side functions to respond to the changes. 

The notification packet informs the event handlers about the virtual path of the updated Realm, as well as the Realm object or objects that have changed. These are broken down by class name and object indexes modified during the last synchronization transaction. 

Creating a Realm Event Handling function involves creating a small Node.js application, with a package.json to define the application and its dependencies. For more information on creating event handlers in Realm Object Server, refer to the Realm Guidelines on Event Handling. 

Next, we’ll start setting up our first Realm function. 

Setting Up Your First Realm Function

For the purposes of this tutorial, we are going to focus on a simple function example to illustrate how functions are created and integrated into the Realm Mobile Platform. It is assumed you already have the existing application from the previous tutorials, hosted on your Realm Object Server and running, before proceeding with the rest of this tutorial. 

First, head off to the Realm Object Server dashboard and select the Functions tab. On this page, Realm already provides you with a sample function that you can enable and run quickly, by first naming the function, choosing which Realm to apply it to (our working app in this case, RealmDoApp), and then starting the function event listener by pressing the Start button. 

Starting a function event listener

Go ahead and do that, while running your iOS app in Xcode Simulator, and create a new reminder task. You will notice the log below is populating with log messages for the different states of your app.

log messages showing the different states of your app

Let’s take a look at the sample code in greater detail: 

The function starts off by exposing the event handing method through exports. Event handling functions take a changeEvent as their parameter. This simple function just outputs the changeEvent.path to the console, showing what is being changed exactly. 

We then get a reference to the changed realm through the changeEvent object, and then get a list of objects and changes. We output a record of all the insertions, modifications, and deletions to the console. 

Extending the Simple Function

This sample function isn’t really functional, but in order to solidify our understanding of what it is possible to do with functions, let’s take the function a bit further and customize it. 

Since it’s a Node.js application, we can work with third-party Node.js libraries. In this instance, we’ll use a library called libphonenumber, and modify our function to parse entries as phone numbers, with the correct formatting and international prefix. 

Before entering the code below, install the third-party library by entering the following into the Realm Object Server:

npm install google-libphonenumber --save

Press Stop in the console to stop the function running, and then modify the function with the following code:

In the above code, we’re creating an instance reference to the third-party library google-libphonenumber, and then getting a list of the reminder objects via realm.objects("Reminder"). Then we get a reference to the last reminder in the array, as it is the most recent one, and then convert its data to a phone number. 

We’ll output the result of that to the console, before actually writing the formatted version of the data back to realm, via:

Give the function another spin by restarting it, and in the iOS Simulator, enter a phone number that isn’t formatted quite correctly, say 17187998177. Through the console log and final output on the app, it should format the number correctly using the third-party library, with the spacing and international prefix as follows:

+1 718-799 8177

What we are seeing here is a serverless way of triggering an event for a change (insertion) and formatting the data prior to persisting it to the cloud.

Specifying Realm URL Path Regular Expressions

In our dashboard function, we simply pointed to a specific Realm application, RealmDo, but you can also define a regular expression (regex) to more uniquely distinguish which paths trigger the function. To match for all Realms, you would use .* (which matches zero or more of any character). Or you could match a user-owned Realm with ^/([0-9a-f]+)/Reminder$.

Conclusion

Realm Functions create new possibilities for the Realm Mobile Platform by providing a simple and elegant way to add serverless logic that is capable of responding to changes in Realms. Through the Dashboard, developers can create functions that respond to changes across all Realms, or just on specific paths. 

In this tutorial, you learned a bit about what Realm Functions are, and how they provide a holistic development environment not only for creating and persisting data but also for adding logic to it. We extended the default function and called a third-party JavaScript library to convert phone numbers. 

While our example is a bit contrived, it provides you with an idea of what you can do to manage Realm objects as they are inserted, modified or deleted. This is just like how traditional databases leverage triggers, only server-less and with minimal code, as you can see. 

While you’re here, take a look at some of our other iOS development posts here on Envato Tuts+.

  • Swift
    What’s New in Swift 4
    Patrick Balestra
  • iOS SDK
    Faster Logins With Password AutoFill in iOS 11
    Patrick Balestra
  • iOS SDK
    15 Best iOS App Templates of 2017
    Nona Blackman

Powered by WPeMatico

Leave a Comment

Scroll to Top