在React中实时渲染RethinkDB结果:react-rethinkdb
react-rethinkdb实现在React中实时渲染RethinkDB结果。
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 | 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 usingfunction(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.
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 inrender()
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'));
eatures
- Realtime queries with RethinkDB changefeed support
- Share results of identical queries across React components
Limitations
- RethinkDB changefeeds don't work on aggregations like.count(), but it will eventually be supported. </li>
- RethinkDB changefeed queries with.orderBy()may not be ordered correctly, but it will eventually be possible.
- https://github.com/rethinkdb/rethinkdb/issues/3714 </ul> </li> </ul>
- Investigate browser compatibility. So far I've only tested in chrome.
- 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. </li>
- 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 </ul> </li>
- 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. </ul> </li>
- Optimistic updates (equivalent to Meteor's latency compensation)
- Reqlite may prove helpful here. </ul> </li> </ul>
Roadmap