Coder Social home page Coder Social logo

react-rethinkdb's Introduction

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 function(actual, refs, session) terms, RQ.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 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:

  • Session.js to create a new websocket connection to the backend/database
  • Mixin.js to enable a React component to subscribe to RethinKDB queries
  • QueryRequest.js to configure queries in subscribed React components
  • QueryResult.js to use results from queries in render()

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

var React = require('react');
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
});

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 = React.findDOMNode(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>;
  },
});

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

Features

  • Realtime queries with RethinkDB changefeed support
  • Share results of identical queries across React components

Limitations

Compatibility

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

  • Chrome 43 (Linux)
  • Chrome 43 (Android 5.0)
  • Chrome 43 (Android 4.4)
  • Chrome 44 (OS X 10.10)
  • Firefox 38 (Linux)
  • Safari 7.1 (OS X 10.9)
  • Safari 8.0 (OS X 10.10)
  • Safari 8.0 (iOS 8.1)
  • IE11 (Win 7)
  • Node.js 0.12 (Linux)

In order to support IE10, the following issue needs to be resolved in the RethinkDB JS driver: rethinkdb/rethinkdb#162

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

Roadmap

  • Investigate performance. I haven't tested with large queries, large numbers of queries, or large result sets.
  • Change mixin API when best practices are established for data loading in React.
  • Support for React components written as ES6 classes
  • React Native support (currently completely untested)
  • Isomorphic app support (currently incomplete)
    • This might be tricky for queries with changefeeds unless we require the browser to rerun the query. But then we might have an extra loading flicker
    • To use on the server in node.js (as opposed to the browser), use the following path when importing the module: var ReactRethinkdb = require('react-rethinkdb/dist/node');
    • See the examples/isomorphic/ directory for example usage
  • Query result caching
    • If a component subscribed to a query is unmounted, and a component is later mounted with the same exact query, the second component should optionally be able to display the cached results.
    • In SubscriptionManager.js, when a component is the last to unsubscribe from a query, instead of removing the query state, we would just close the query but keep the state around (marked as stale) in case another component later subscribes. We may even set a timer before closing the query and marking it stale in case it's common for components to quickly resubscribe.
    • Components may specify if they are fine with stale results or if they need a refresh.
    • We will need an invalidation policy so we don't leak memory.
  • Optimistic updates (equivalent to Meteor's latency compensation)

react-rethinkdb's People

Contributors

mikemintz avatar

Watchers

Christopher Tarquini avatar James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.