神刀安全网

DIY Meteor-like Realtime Functionality Using Socket.io and RethinkDB Changefeeds

RethinkDB is the latest major entrant NoSQL database. Having used it in production to build my current startup, it is in my opinion one of the best databases for a reactive web app. The key feature that makes it so powerful are changefeeds. These are essentially defined ReQL queries tied to an event listener (callbacks). Every time a document is changed, added, or removed that is selected by the query, the changefeed passes the updated document(s) to the event listener. If you’re anything like me, I’m sure your mind is already spinning with the possibilities!

Meteor made use of MongoDB oplog tailing to push database changes up to the client (i.e. the client app did not need to regularly poll the backend for updates). Building on this idea, this is how I’ve used RethinkDB changefeeds to push database changes to the client of a WebSocket, thus, keeping client and server data in seamless sync. Let’s see how this works.

Notes:

  • The only language used in this tip is JavaScript (node.js)
  • Assuming you already have a working Node app, with the RethinkDB module installed, and connected to a running RethinkDB database. We’ll reference ‘connection’ as the pointer to the RethinkDB connection, and ‘r’ as the RethinkDB JS library
  • No Client side code is covered, so you could use React, Angular, or any framework that has a client side immutable data store with getters and setters (i.e. this.setState({}) and this.state in React.js)
  • This post assumes you have some knowledge of Socket.io , and have a socket setup as ‘socket’

Let’s say we have a table in RethinkDB called Fruit, with the documents:

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » DIY Meteor-like Realtime Functionality Using Socket.io and RethinkDB Changefeeds

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮