Skip to content

Instantly share code, notes, and snippets.

@7c
Created May 30, 2023 12:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 7c/18c2985d69a2ea142cd50cece40d5d18 to your computer and use it in GitHub Desktop.
Save 7c/18c2985d69a2ea142cd50cece40d5d18 to your computer and use it in GitHub Desktop.
const chalk = require('chalk')
// used to keep the connection to mongo alive
// tested with mongodb@4 nodejs driver
class Mongo4Manager {
mongoHandle = null
constructor(dsn, connectionOptions = {},retryInterval = 1000, pingInterval = 1000) {
this.connectionOptions = connectionOptions
this.dsn = dsn
this.retryInterval = retryInterval
this.pingInterval = pingInterval
}
client() {
return this.mongoHandle
}
pinger(handle, pingInterval, that) {
// console.log(`pinger(${pingInterval})`)
setTimeout(() => {
if (handle)
handle.db("admin").command({ ping: 1 }).then((x) => {
// console.log(`Starting new pinger`, x)
this.pinger(handle, pingInterval,that)
}).catch(err => {
console.log(chalk.red(err.toString()), 'MONGO PING')
// detected an error
that.connect()
return
})
}, pingInterval)
}
connect() {
const { MongoClient } = require("mongodb")
console.log(chalk.yellow(`connect()`))
this.mclient = new MongoClient(this.dsn, { heartbeatFrequencyMS: 5000, serverSelectionTimeoutMS: 5000, ...this.connectionOptions })
this.mclient.connect().then(async () => {
console.log(chalk.green.inverse("Connected successfully to mongodb server"))
this.mongoHandle = this.mclient
this.pinger(this.mongoHandle, this.pingInterval,this)
}).catch(err => {
this.mongoHandle = false
console.log(chalk.red(err.toString()),'CONNECT')
console.log(`Will reconnect after ${this.retryInterval} ms`)
setTimeout(() => { this.connect(), this.retryInterval })
})
}
}
module.exports = Mongo4Manager
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment