connection.js 4.6 KB

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