Hi Rick,
your original implementation strikes me as better than the other one.
Since storing something in Redis means serialising it, you won’t get the
benefit of any sockets being kept open, and I’m not even sure you can make that
work properly.
If you are worried about having a db instance open per request vs
once-per-server-per-user, how about this slight modification to your original
pattern. This is something we’re using in Opservatory* for the same reason:
let dbs = {}
function getDb(orgname) {
if (!dbs[orgname] {
// cache db instance if not already cached
dbs[orgname] = nano.db.use(orgname);
}
// return cached db instance
return dbs[orgname]
}
app.use(function(req, res, next) {
const orgname = req.headers.host.split('.')[0].toLowerCase();
req.couch = getDb(orgname)
next();
}
If you have very long running servers and high user churn, you also want to
make sure you can drop cached instances from `dbs` when a user gets deleted. Or
you add a max length check to this and drop the least recently used instance,
but you get the idea.
Best
Jan
—
Professional Support for Apache CouchDB:
https://neighbourhood.ie/couchdb-support/
*24/7 Observation for your CouchDB Instances:
https://opservatory.app
> On 4. Jul 2021, at 19:02, Rick Jarvis <[email protected]> wrote:
>
> Hey all
>
> I have an app which serves multiple orgs with individual databases, by way of
> subdomain, ORGNAME.myapp.foo . My current method of attaching the database to
> the ExpressJS requests via middleware is like this:
>
> app.use(function(req, res, next) {
> const orgname = req.headers.host.split('.')[0].toLowerCase();
> req.couch = nano.db.use(orgname);
> next();
> }
>
> I often wonder if this is the best way of doing it. Is there a better way?
>
> I could for instance, attach it just once, to the session (stored in Redis):
>
> app.use(function(req, res, next) {
> if(!req.session.couch) {
> const orgname = req.headers.host.split('.')[0].toLowerCase();
> req.session.couch = nano.db.use(orgname);
> }
> next();
> }
>
> But I guess that depends on size of the Couch instance (is it just metadata,
> or something more tangible?), and other aspects which I perhaps haven’t
> considered.
>
> I’d love to hear some thoughts on this?
>
> Thank you!
> R