connection.js 5.9 KB

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