RethinkDB Connection Middleware

I needed to add a per-request RethinkDB connection to an Express app I was writing. Here's a piece of Express 4.x middleware which does that and cleans-up after itself:

var r = require('rethinkdb');

module.exports = function (opts) {  
  opts = opts || {};
  opts.propName = opts.propName || 'db';

  return function (req, res, next) {
    res.on('finish', function () {
      req[opts.propName].close();
    });

    r.connect(opts, function (err, conn) {
      req[opts.propName] = conn;
      next(error);
    });
  };
};

To use it:

var app = require('express'),  
    rdb = require(/* path to above */);

app.use(rdb({  
    db: 'test',
    host: 'localhost',
    propName: '_rdb'
}));