Reusing code on the client and the server

We have a solution which uses Node.js and MongoDB today and we’re
exploring options for making our app Offline-first. Realms looks
really promising.

This is an IoT device management solution. The IoT devices normally
send their state directly to the cloud, and then the client app uses a
REST API to fetch the data from the backend.

But because the IoT devices sometimes have poor connectivity we also
want to enable you to use the app as a gateway for data from the IoT
device. So for example you can connect to the device directly,
download data from it, store that data locally on your phone, and then
get that data synced to the cloud when you’re back in coverage. But
when you do this, we want the updated state from the devices to show
in your app.

This means we want the same business logic that currently runs on the
server to also run on the phone, so that the phone can show the
correct device state even when both the device and the phone are
offline.

Example: The device sends a state message { “device”: 1, “state”:
“off” }. Normally this would go to our backend which will update the
MongoDB database, and then the client fetches an updated view where
the state of device 1 is “off”. The path the data takes from device to
app can be depicted like this:

device -> backend -> mongodb -> realm -> app

But if the app connects directly to the device and
gets the state from the device using Blueooth Low Energy, then the
data path will be:

device -> app -> realm -> mongodb

And this means we need to duplicate the code that handles the incoming
state. In the backend it has to write directly to mongodb, and in the
app it writes to the realm. We really want the app to run what is
essentially a “mini-backend” that can contain the same code as the
cloud server.

It appears the only way to achieve this is to introduce realms on the
server too, so the first path above would become:

device → backend → realm(cloud) → mongodb → realm(app) → app

And this doesn’t feel right. Every incoming message from an IoT Device
would then have to open a new Realm, and every direct message from the
devices would then need to pass through that extra realm sync just to
get to the backend database.

Any ideas on how to solve this?