DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • ArangoDB: Achieving Success With a Multivalue Database

Trending

  • System Coexistence: Bridging Legacy and Modern Architecture
  • Start Coding With Google Cloud Workstations
  • MCP Servers: The Technical Debt That Is Coming
  • A Deep Dive Into Firmware Over the Air for IoT Devices
  1. DZone
  2. Data Engineering
  3. Databases
  4. Arangochair: A Tool for Listening to Changes in ArangoDB

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.

By 
Manuel Baesler user avatar
Manuel Baesler
·
Mar. 11, 17 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
5.8K Views

Join the DZone community and get the full member experience.

Join For Free

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.

ArangoDB

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

Opinions expressed by DZone contributors are their own.

Related

  • ArangoDB: Achieving Success With a Multivalue Database

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: