mikemintz / react-rethinkdb

Render realtime RethinkDB results in React
MIT License
870 stars 48 forks source link

npm version Travis

react-rethinkdb

Render realtime RethinkDB results in React

Get started

To get started immediately, follow the examples/tutorial/ project, or clone some of the other projects in examples/.

What is this?

This library provides a React mixin for running RethinkDB queries in any React component directly from the browser. It wraps rethinkdb-websocket-client to connect to the database, and is intended to be used with rethinkdb-websocket-server running in the backend.

This is similar to solutions like Meteor, Parse, and Firebase. Rather than writing database queries in the backend and exposing API endpoints to the frontend, these solutions allow the frontend to directly access the data layer (secured by a permission system) using the same query API that backend services have access to.

React support Database Realtime Open-source
react-rethinkdb RethinkDB
Meteor react-meteor and react-packages MongoDB
Parse ParseReact MongoDB
Firebase ReactFire MongoDB

What is React?

React is a JavaScript library for building user interfaces. It's pretty cool.

This library only works with React by design. If you are interested in connecting to RethinkDB from the browser without React, you can use rethinkdb-websocket-client.

What is RethinkDB?

RethinkDB is an open-source NoSQL database with baked in realtime capabilities. It is quite popular, it is the second most starred database on GitHub after Redis.

Is this secure?

Although it seems quite insecure to run database queries directly from the frontend, all queries should be validated by rethinkdb-websocket-server before they are forwarded to RethinkDB. From its README:

As you are developing, incoming queries that don't validate against the whitelist will be logged to console in a format that you can copy and paste directly into your JavaScript source file. For dynamic queries, you'll likely want to generalize the pattern using RP.check() terms, RP.ref() terms, and the .validate() method.

See examples/chat/ for an example app that has user authentication and query validation in the backend.

Most of the query validation logic can be found in QueryValidator.js.

How do I use this?

Check out the examples/ folder in this repository for fully-working React applications. You will need to install RethinkDB version 2.2 or newer first if you haven't already.

The examples/tutorial/ project has in-depth instructions explaining how to create a simple app from scratch.

You can also peruse the comments in the source code in the src/ directory:

Below is a very simple React application to give an idea of the syntax:

var React = require('react');
var ReactDOM = require('react-dom');
var ReactRethinkdb = require('react-rethinkdb');
var r = ReactRethinkdb.r;

ReactRethinkdb.DefaultSession.connect({
  host: 'localhost',          // hostname of the websocket server
  port: 8015,                 // port number of the websocket server
  path: '/',                  // HTTP path to websocket route
  secure: false,              // set true to use secure TLS websockets
  db: 'test',                 // default database, passed to rethinkdb.connect
  autoReconnectDelayMs: 2000, // when disconnected, millis to wait before reconnect
});

var App = React.createClass({
  mixins: [ReactRethinkdb.DefaultMixin],

  observe: function(props, state) {
    return {
      turtles: new ReactRethinkdb.QueryRequest({
        query: r.table('turtles'), // RethinkDB query
        changes: true,             // subscribe to realtime changefeed
        initial: [],               // return [] while loading
      }),
    };
  },

  handleSubmit: function(event) {
    event.preventDefault();
    var nameInput = this.refs.firstName;
    var query = r.table('turtles').insert({firstName: nameInput.value});
    nameInput.value = '';
    ReactRethinkdb.DefaultSession.runQuery(query);
  },

  render: function() {
    var turtleDivs = this.data.turtles.value().map(function(x) {
      return <div key={x.id}>{x.firstName}</div>;
    });
    return <div>
      <form onSubmit={this.handleSubmit}>
        <input type="text" ref="firstName" />
        <input type="submit" />
      </form>
      {turtleDivs}
    </div>;
  },
});

ReactDOM.render(<App />, document.getElementById('app'));

Features

Limitations

Compatibility

So far, this library has been tested successfully in the following environments:

In IE10, your queries must use r.bracket instead of function-call shorthand. E.g. r.table('turtles').get(id)("name") must be written as r.table('turtles').get(id).bracket("name"). See rethinkdb#162 for more details.

IE9 and old android browsers are not supported because they don't have WebSockets, and rethinkdb-websocket-client currently requires WebSocket support.

Upgrade guide

Most new versions of react-rethinkdb are backwards compatible with previous versions. Below are exceptions with breaking changes:

Upgrading to 0.5 (from 0.4)

Version 0.5 of react-rethinkdb saw the introduction of atomic changefeeds, which is a new feature in RethinkDB 2.2. This simplifies the logic by sending one "atomic" changefeed query, rather than a static query for initial results followed by a changefeed query for realtime updates. This saves bandwidth and prevents the race condition where data changes in between the two queries.

Regular static queries will continue to work the same. But in order to use react-rethinkdb 0.5 with changefeed queries, you must both:

r.table("tortoises")
 .changes({
   includeStates: true,
   includeInitial: true, // this line is now required
 })
 .opt("db", r.db("test")),

Or with the old syntax:

RQ(
  RQ.CHANGES(
    RQ.TABLE("tortoises")
  ).opt("include_states", true)
   .opt("include_initial", true) // this line is now required
).opt("db", RQ.DB("test")),

Roadmap