Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Arangochair: A Tool for Listening to Changes in ArangoDB

DZone's Guide to

Arangochair: A Tool for Listening to Changes in ArangoDB

In this post we take a look at arangochair, a module for monitoring to changes triggered in ArangoDB and reacting to them with specific actions.

· Database Zone
Free Resource

Learn how to move from MongoDB to Couchbase Server for consistent high performance in distributed environments at any scale.

The ArangoDB team gave me an opportunity to write a tutorial about arangochair. Arangochair is the first attempt to listen for changes in the database and execute actions like pushing a document to the client or executing an AQL query. Currently, it is limited to single nodes.

This tutorial is loosely based on the example at baslr/arangochair-serversendevents-demo

Arangochair is a Node.js module hosted on npm, which makes it fairly easy to install. Just run
npm install arangochair, and it's installed.

Now We Can Write Our First Lines of Code

We set up arangochair to listen for changes on the collection tweets and construct a server send event message and sent it to all connected sockets. The SSE consists of two lines per message. The first line is the event and the second line is a stringified line of JSON.

const changes = new arangochair('http://127.0.0.1:8529'); // ArangoDB node to monitor

changes.subscribe({collection:'tweets'});
changes.start();
changes.on('tweets', (docIn, type) => {
    const doc = JSON.parse(docIn);

    const message = 'event: ' + type + '\ndata: ' + JSON.stringify(doc) + '\n\n';
    for(const sse of sses) {
        sse.write(message);
    }
});

no4.on('error', (err, httpStatus, headers, body) => {
    console.log('on error', err);
    // arangochair stops on errors
    // check last http request
    no4.start();
});


On the client side, we use the EventSource interface to listen for events that we send on the server.

First, we construct a new EventSource and add two EventListeners to listen for insert/update and delete. Separate events for insert and update are currently not possible but will be part of a future update.

const events = new EventSource('/sse');

events.addEventListener('delete', (e) => {
      const doc = JSON.parse(e.data);
      // do something
}, false);
events.addEventListener('insert/update', (e) => {
      const doc = JSON.parse(e.data);
      // do something
}, false);


Handle Socket Connections on the Server With Express

In this example, we use express as our framework to handle API calls. We write a middleware that handles the socket of a client to receive SSEs. If the client connection ends we remove the socket from the array of stored sockets.

app.use( (req, res, next) => {
    if ('/sse' === req.url) {
        sses.push(res);
        res.setHeader('Content-Type', 'text/event-stream');
        res.on('close', () => {
            const idx = sses.indexOf(res);
            if (-1 === idx) return;
            sses.splice(idx, 1);
        });

        res.write('data: initial\n\n');
    } else {
   next();
    }
});


Why Not WebSockets?

Since we want only push data to the client we do not need a duplex connection. Also, SSE uses a traditional HTTP connection without a special protocol and reconnects itself on connection loss.

Want to deliver a whole new level of customer experience? Learn how to make your move from MongoDB to Couchbase Server.

Topics:
arangodb ,database ,arangochair ,database monitoring ,tutorial

Published at DZone with permission of Manuel Baesler, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}