I have played with a local RethinkDB installation. Now I wanted to see how simple / difficult is to get a hosted instance. I signed up for a free trial at compose.io, a DB as a service provider. The initial setup took 60 seconds, and the cluster with two servers was ready. In order to connect and see the web admin interface I had to
- Create new user and copy my public SSH key
- Run ssh tunnel with port forwarding. The default mapping from remote port to
127.0.0.2:8080
address did not work, so I mapped tolocalhost:8082
port instead. This worked and I could openlocalhost:8082
in the browser and see the hosted database interface, just as if it were locally run instance.
1 | ssh -N [email protected] -p 10000 \ |
Similarly, I mapped ports for a driver to connect to the remote DB via local port. The default RethinkDB driver connection port is 28015 and we can map it to our local port 27000 for example.
1 | ssh -N [email protected] -p 10000 \ |
Trying remote DB
The remote database is accessible via localhost
and mapped port. All I needed to do was
to provide these parameters as arguments to the thinky
.
1 | var options = { |
The rest of the script can be in my Try RethinkDB blog post. The remote server has received the data and I could see it via the admin web interface.
Access DB from an API server
We should not access the database directly from a web server, instead I prefer wrapping the data in a dedicated REST server. To do so I created a simple application on Heroku that uses Express server to parse input parameters and output JSON.
Access DB from Heroku app
To allow an application hosted on Heroku to connect to the RethinkDB I had to add ssh tunnel command
to the [Procfile][https://devcenter.heroku.com/articles/procfile]. This command runs when the dyno starts
and makes the remote database appear as a local one at the specific address (like localhost:28015
).
1 | web: /bin/bash -c '(nohup ssh -n -i compose-heroku-key -o StrictHostKeyChecking=no \ |
After adding a tunnel, the Procfile tells the Heroku boot process to run node index.js
which is our Express server.
Return data on GET
First, I configured an Express server using Getting Started with Bookshelf.js as an example. The express server configuration deals with JSON only
1 | var express = require('express'); |
The RethinkDB-specific setup only had Thinky stuff
1 | var options = { |
Then I added first route to return all tv shows
1 | app.get('/api/tv_shows', function(req, res) { |
and another route to return specific tv show JSON given an id
1 | app.get('/api/tv_shows/:id', function(req, res) { |
This setup allows only getting the data, not adding new records or editing yet.
Extras
- Blog example using Thinky + Express
- Good intro to writing REST api using MongoDB + Express.
- Another good tutorial showing routing and testing REST using Postman is Build a RESTful API Using Node and Express 4