Reputation: 40448
Do I open and close a connection to a RethinkDB server on every HTTP request? I was reading a tutorial of the official examples. It describes an Express app and it basically looks like:
var app = express();
app.use(openConnection);
app.use(/* do stuff */);
app.use(closeConnection);
Is this considered best practice or is this the only practice since there is no native connection pooling or other approaches?
Upvotes: 0
Views: 594
Reputation: 4614
When it comes to how to deal with connections, there are a couple of options:
Single Connection
The simplest option is to just open a single connection and use it through out your app. This is extremely simple but probably doesn't work for larger applications where you might be executing a lot of requests.
In JavaScript, the connection can be appended to the r
object and used throughout the application.
import r from 'rethinkdb';
import express from 'express';
let app = express();
r.connect().then((conn) => {
r.conn = conn;
});
app.use('/table-list', (req, res) => {
r.db('test').tableList().run(conn)
.then((result) => {
return res.json(result);
});
});
Open & Close
You can also just open and close a connection every single time you do a request. This approach is also simple, but it's a bit more verbose.
r.connect().then((conn) =>
return r.db('test').tableList().run(conn)
.then((result) => {
console.log(result);
return result;
})
.then(() => {
conn.close();
});
});
Per Request Connection
As you noted earlier, you can also open a connection per-request, use that connection throughout the request, and then close it when the request is done.
Connection Pooling
Finally, you can also use connection pooling if you use rethinkdbdash, which abstracts away connections for you.
Upvotes: 1