packages/mongo/lib/utils.js
// Utility function to setup a connection
Utility function to setup a connection
Utility function to setup a connection
async function connect (mongoose, connectionName, connectionOpts) {
  const isDefault = connectionName === 'default'
  if (typeof connectionOpts === 'string') {
    connectionOpts = { uri: connectionOpts }
  }
  let { uri, options, forceReconnect } = connectionOpts
  options = {
    useNewUrlParser: true,
    useCreateIndex: true,
    ...options
  }
  let conn
  if (isDefault) {
    conn = mongoose.connection
  } else {
    conn = new mongoose.Connection(mongoose)
    mongoose.connections.push(conn)
  }
  conn.$logger = isDefault
    ? consola
    : consola.withTag(connectionName)
  logConnectionEvents(conn)
  conn.$connect = () => {
    return new Promise((resolve, reject) => {
      conn.openUri(uri, options, (error) => {
        if (error) {
          reject(error)
        } else {
          resolve(conn)
        }
      })
    })
  }
  mongoose['$' + connectionName] = conn
  if (forceReconnect) {
    const timeout = forceReconnect === true ? 1000 : forceReconnect
    conn.on('error', () => {
      conn.close()
    })
    conn.on('disconnected', () => {
      setTimeout(() => { conn.$connect() }, timeout)
    })
  }
  await conn.$connect()
  await conn.$initialConnection
}
async function connect ( mongoose , connectionName , connectionOpts ) { const isDefault = connectionName === 'default' if ( typeof connectionOpts === 'string' ) { connectionOpts = { uri : connectionOpts } } let { uri , options , forceReconnect } = connectionOpts options = { useNewUrlParser : true , useCreateIndex : true , ... options } let conn if ( isDefault ) { conn = mongoose . connection } else { conn = new mongoose . Connection ( mongoose ) mongoose . connections . push ( conn ) } conn . $logger = isDefault ? consola : consola . withTag ( connectionName ) logConnectionEvents ( conn ) conn . $connect = ( ) => { return new Promise ( ( resolve , reject ) => { conn . openUri ( uri , options , ( error ) => { if ( error ) { reject ( error ) } else { resolve ( conn ) } } ) } ) } mongoose [ '$' + connectionName ] = conn if ( forceReconnect ) { const timeout = forceReconnect === true ? 1000 : forceReconnect conn . on ( 'error' , ( ) => { conn . close ( ) } ) conn . on ( 'disconnected' , ( ) => { setTimeout ( ( ) => { conn . $connect ( ) } , timeout ) } ) } await conn . $connect ( ) await conn . $initialConnection }
Utility function to setup a connection
Utility function to setup a connection
// Normalize and destructure connection options // Apply default options // https://mongoosejs.com/docs/connections.html#options // Manualy create connection // $logger helper // Log connection events // $connect helper // Make accessable via mongoose.$connectionName // Setup force reconnect // Connect