All files / copacetic/lib/health-strategies/mongodb/adapters mongoose.js

88.88% Statements 24/27
66.66% Branches 4/6
100% Functions 14/14
88.46% Lines 23/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82              13x 13x             13x               7x 7x   7x 5x     7x 2x 2x     7x 2x                 3x 2x 2x 2x       2x         1x                   3x 3x 3x         3x           13x  
/**
 * An adapter for the mongoose library
 * https://github.com/Automattic/mongoose
 * @class
 */
class MongooseAdapter {
  constructor (mongoose) {
    this.client = mongoose
    this.connection = null
  }
 
  /**
   * @return {Boolean} Whether there is an active mongo connection
   */
  get isConnected () {
    return this.connection !== null
  }
 
  /**
   * @param {String} url Redis connection url
   * @param {Number} connectTimeout How long to wait when connecting, before timing out
   */
  connect (url, connectTimeoutMS) {
    return new Promise((resolve, reject) => {
      this.connection = this.client.createConnection(url, { connectTimeoutMS })
 
      this.connection.on('connected', () => {
        return resolve(true)
      })
 
      this.connection.on('error', (err) => {
        this.connection = null
        return reject(err)
      })
 
      this.connection.on('close', () => {
        this.connection = null
      })
    })
  }
 
  /**
   * Destroys the mongodb connection
   */
  close () {
    if (this.connection !== null) {
      return new Promise((resolve, reject) => {
        this.connection.close((err) => {
          Iif (err) {
            return reject(err)
          }
 
          return resolve(true)
        })
      })
    }
 
    return Promise.reject(
      new Error('tried to close a connection to mongo, but one does not exist')
    )
  }
 
  /**
   * Attempts to ping mongodb
   * @return {Promise.<Boolean>|Error>}
   */
  ping () {
    return new Promise((resolve, reject) => {
      this.connection.db.admin().ping((err, result) => {
        Iif (err) {
          this.connection = null
          return reject(err)
        }
 
        return resolve(true)
      })
    })
  }
}
 
module.exports = mongoose => new MongooseAdapter(mongoose)