Yeah, I would probably do something similar to what you're describing. I couldn't tell you if this code is fully functional, but here's a five-minute go at it:
class TimedConnection {
constructor(uri) {
this.uri = uri;
this._connected = false;
this.disconnect = this.disconnect.bind(this);
}
connect() {
return new Promise((resolve, reject) => {
if (!this._connected) {
const db = this.db = mongoose.createConnection(this.uri);
db.once('open', resolve());
// whatever
}
clearTimeout(this._connectionTimeout);
this._connectionTimeout = setTimeout(this.disconnect, 300000)
return resolve(this.db);
})
}
query() {
this.connect().then((db) => {
// something with `db`
})
}
disconnect() {
this.db.disconnect();
this._connected = false;
}
}
const connectionMap = {
objectsDatabase: new TimedConnection('mongodb://whatever'),
personsDatabase: new TimedConnection('mongodb://whateverthing'),
...
};