connection.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. /*!
  2. * Module dependencies.
  3. */
  4. 'use strict';
  5. const MongooseConnection = require('../../connection');
  6. const STATES = require('../../connectionstate');
  7. /**
  8. * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) connection implementation.
  9. *
  10. * @inherits Connection
  11. * @api private
  12. */
  13. function NativeConnection() {
  14. MongooseConnection.apply(this, arguments);
  15. this._listening = false;
  16. }
  17. /**
  18. * Expose the possible connection states.
  19. * @api public
  20. */
  21. NativeConnection.STATES = STATES;
  22. /*!
  23. * Inherits from Connection.
  24. */
  25. NativeConnection.prototype.__proto__ = MongooseConnection.prototype;
  26. /**
  27. * Switches to a different database using the same connection pool.
  28. *
  29. * Returns a new connection object, with the new db. If you set the `useCache`
  30. * option, `useDb()` will cache connections by `name`.
  31. *
  32. * @param {String} name The database name
  33. * @param {Object} [options]
  34. * @param {Boolean} [options.useCache=false] If true, cache results so calling `useDb()` multiple times with the same name only creates 1 connection object.
  35. * @return {Connection} New Connection Object
  36. * @api public
  37. */
  38. NativeConnection.prototype.useDb = function(name, options) {
  39. // Return immediately if cached
  40. if (options && options.useCache && this.relatedDbs[name]) {
  41. return this.relatedDbs[name];
  42. }
  43. // we have to manually copy all of the attributes...
  44. const newConn = new this.constructor();
  45. newConn.name = name;
  46. newConn.base = this.base;
  47. newConn.collections = {};
  48. newConn.models = {};
  49. newConn.replica = this.replica;
  50. newConn.config = Object.assign({}, this.base.connection.config, newConn.config);
  51. newConn.name = this.name;
  52. newConn.options = this.options;
  53. newConn._readyState = this._readyState;
  54. newConn._closeCalled = this._closeCalled;
  55. newConn._hasOpened = this._hasOpened;
  56. newConn._listening = false;
  57. newConn.host = this.host;
  58. newConn.port = this.port;
  59. newConn.user = this.user;
  60. newConn.pass = this.pass;
  61. // First, when we create another db object, we are not guaranteed to have a
  62. // db object to work with. So, in the case where we have a db object and it
  63. // is connected, we can just proceed with setting everything up. However, if
  64. // we do not have a db or the state is not connected, then we need to wait on
  65. // the 'open' event of the connection before doing the rest of the setup
  66. // the 'connected' event is the first time we'll have access to the db object
  67. const _this = this;
  68. newConn.client = _this.client;
  69. if (this.db && this._readyState === STATES.connected) {
  70. wireup();
  71. } else {
  72. this.once('connected', wireup);
  73. }
  74. function wireup() {
  75. newConn.client = _this.client;
  76. newConn.db = _this.client.db(name);
  77. newConn.onOpen();
  78. // setup the events appropriately
  79. listen(newConn);
  80. }
  81. newConn.name = name;
  82. // push onto the otherDbs stack, this is used when state changes
  83. this.otherDbs.push(newConn);
  84. newConn.otherDbs.push(this);
  85. // push onto the relatedDbs cache, this is used when state changes
  86. if (options && options.useCache) {
  87. this.relatedDbs[newConn.name] = newConn;
  88. newConn.relatedDbs = this.relatedDbs;
  89. }
  90. return newConn;
  91. };
  92. /*!
  93. * Register listeners for important events and bubble appropriately.
  94. */
  95. function listen(conn) {
  96. if (conn.db._listening) {
  97. return;
  98. }
  99. conn.db._listening = true;
  100. conn.db.on('close', function(force) {
  101. if (conn._closeCalled) return;
  102. // the driver never emits an `open` event. auto_reconnect still
  103. // emits a `close` event but since we never get another
  104. // `open` we can't emit close
  105. if (conn.db.serverConfig.autoReconnect) {
  106. conn.readyState = STATES.disconnected;
  107. conn.emit('close');
  108. return;
  109. }
  110. conn.onClose(force);
  111. });
  112. conn.db.on('error', function(err) {
  113. conn.emit('error', err);
  114. });
  115. conn.db.on('reconnect', function() {
  116. conn.readyState = STATES.connected;
  117. conn.emit('reconnect');
  118. conn.emit('reconnected');
  119. conn.onOpen();
  120. });
  121. conn.db.on('timeout', function(err) {
  122. conn.emit('timeout', err);
  123. });
  124. conn.db.on('open', function(err, db) {
  125. if (STATES.disconnected === conn.readyState && db && db.databaseName) {
  126. conn.readyState = STATES.connected;
  127. conn.emit('reconnect');
  128. conn.emit('reconnected');
  129. }
  130. });
  131. conn.db.on('parseError', function(err) {
  132. conn.emit('parseError', err);
  133. });
  134. }
  135. /**
  136. * Closes the connection
  137. *
  138. * @param {Boolean} [force]
  139. * @param {Function} [fn]
  140. * @return {Connection} this
  141. * @api private
  142. */
  143. NativeConnection.prototype.doClose = function(force, fn) {
  144. this.client.close(force, (err, res) => {
  145. // Defer because the driver will wait at least 1ms before finishing closing
  146. // the pool, see https://github.com/mongodb-js/mongodb-core/blob/a8f8e4ce41936babc3b9112bf42d609779f03b39/lib/connection/pool.js#L1026-L1030.
  147. // If there's queued operations, you may still get some background work
  148. // after the callback is called.
  149. setTimeout(() => fn(err, res), 1);
  150. });
  151. return this;
  152. };
  153. /*!
  154. * Module exports.
  155. */
  156. module.exports = NativeConnection;