mongo_client.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.MongoClient = exports.ServerApiVersion = void 0;
  4. const bson_1 = require("./bson");
  5. const change_stream_1 = require("./change_stream");
  6. const connection_string_1 = require("./connection_string");
  7. const db_1 = require("./db");
  8. const error_1 = require("./error");
  9. const mongo_types_1 = require("./mongo_types");
  10. const connect_1 = require("./operations/connect");
  11. const promise_provider_1 = require("./promise_provider");
  12. const utils_1 = require("./utils");
  13. /** @public */
  14. exports.ServerApiVersion = Object.freeze({
  15. v1: '1'
  16. });
  17. /** @internal */
  18. const kOptions = Symbol('options');
  19. /**
  20. * The **MongoClient** class is a class that allows for making Connections to MongoDB.
  21. * @public
  22. *
  23. * @remarks
  24. * The programmatically provided options take precedent over the URI options.
  25. *
  26. * @example
  27. * ```js
  28. * // Connect using a MongoClient instance
  29. * const MongoClient = require('mongodb').MongoClient;
  30. * const test = require('assert');
  31. * // Connection url
  32. * const url = 'mongodb://localhost:27017';
  33. * // Database Name
  34. * const dbName = 'test';
  35. * // Connect using MongoClient
  36. * const mongoClient = new MongoClient(url);
  37. * mongoClient.connect(function(err, client) {
  38. * const db = client.db(dbName);
  39. * client.close();
  40. * });
  41. * ```
  42. *
  43. * @example
  44. * ```js
  45. * // Connect using the MongoClient.connect static method
  46. * const MongoClient = require('mongodb').MongoClient;
  47. * const test = require('assert');
  48. * // Connection url
  49. * const url = 'mongodb://localhost:27017';
  50. * // Database Name
  51. * const dbName = 'test';
  52. * // Connect using MongoClient
  53. * MongoClient.connect(url, function(err, client) {
  54. * const db = client.db(dbName);
  55. * client.close();
  56. * });
  57. * ```
  58. */
  59. class MongoClient extends mongo_types_1.TypedEventEmitter {
  60. constructor(url, options) {
  61. super();
  62. this[kOptions] = (0, connection_string_1.parseOptions)(url, this, options);
  63. // eslint-disable-next-line @typescript-eslint/no-this-alias
  64. const client = this;
  65. // The internal state
  66. this.s = {
  67. url,
  68. sessions: new Set(),
  69. bsonOptions: (0, bson_1.resolveBSONOptions)(this[kOptions]),
  70. namespace: (0, utils_1.ns)('admin'),
  71. get options() {
  72. return client[kOptions];
  73. },
  74. get readConcern() {
  75. return client[kOptions].readConcern;
  76. },
  77. get writeConcern() {
  78. return client[kOptions].writeConcern;
  79. },
  80. get readPreference() {
  81. return client[kOptions].readPreference;
  82. },
  83. get logger() {
  84. return client[kOptions].logger;
  85. }
  86. };
  87. }
  88. get options() {
  89. return Object.freeze({ ...this[kOptions] });
  90. }
  91. get serverApi() {
  92. return this[kOptions].serverApi && Object.freeze({ ...this[kOptions].serverApi });
  93. }
  94. /**
  95. * Intended for APM use only
  96. * @internal
  97. */
  98. get monitorCommands() {
  99. return this[kOptions].monitorCommands;
  100. }
  101. set monitorCommands(value) {
  102. this[kOptions].monitorCommands = value;
  103. }
  104. get autoEncrypter() {
  105. return this[kOptions].autoEncrypter;
  106. }
  107. get readConcern() {
  108. return this.s.readConcern;
  109. }
  110. get writeConcern() {
  111. return this.s.writeConcern;
  112. }
  113. get readPreference() {
  114. return this.s.readPreference;
  115. }
  116. get bsonOptions() {
  117. return this.s.bsonOptions;
  118. }
  119. get logger() {
  120. return this.s.logger;
  121. }
  122. connect(callback) {
  123. if (callback && typeof callback !== 'function') {
  124. throw new error_1.MongoInvalidArgumentError('Method `connect` only accepts a callback');
  125. }
  126. return (0, utils_1.maybePromise)(callback, cb => {
  127. (0, connect_1.connect)(this, this[kOptions], err => {
  128. if (err)
  129. return cb(err);
  130. cb(undefined, this);
  131. });
  132. });
  133. }
  134. close(forceOrCallback, callback) {
  135. if (typeof forceOrCallback === 'function') {
  136. callback = forceOrCallback;
  137. }
  138. const force = typeof forceOrCallback === 'boolean' ? forceOrCallback : false;
  139. return (0, utils_1.maybePromise)(callback, callback => {
  140. if (this.topology == null) {
  141. return callback();
  142. }
  143. // clear out references to old topology
  144. const topology = this.topology;
  145. this.topology = undefined;
  146. topology.close({ force }, error => {
  147. if (error)
  148. return callback(error);
  149. const { encrypter } = this[kOptions];
  150. if (encrypter) {
  151. return encrypter.close(this, force, error => {
  152. callback(error);
  153. });
  154. }
  155. callback();
  156. });
  157. });
  158. }
  159. /**
  160. * Create a new Db instance sharing the current socket connections.
  161. *
  162. * @param dbName - The name of the database we want to use. If not provided, use database name from connection string.
  163. * @param options - Optional settings for Db construction
  164. */
  165. db(dbName, options) {
  166. options = options !== null && options !== void 0 ? options : {};
  167. // Default to db from connection string if not provided
  168. if (!dbName) {
  169. dbName = this.options.dbName;
  170. }
  171. // Copy the options and add out internal override of the not shared flag
  172. const finalOptions = Object.assign({}, this[kOptions], options);
  173. // Return the db object
  174. const db = new db_1.Db(this, dbName, finalOptions);
  175. // Return the database
  176. return db;
  177. }
  178. static connect(url, options, callback) {
  179. if (typeof options === 'function')
  180. (callback = options), (options = {});
  181. options = options !== null && options !== void 0 ? options : {};
  182. try {
  183. // Create client
  184. const mongoClient = new MongoClient(url, options);
  185. // Execute the connect method
  186. if (callback) {
  187. return mongoClient.connect(callback);
  188. }
  189. else {
  190. return mongoClient.connect();
  191. }
  192. }
  193. catch (error) {
  194. if (callback)
  195. return callback(error);
  196. else
  197. return promise_provider_1.PromiseProvider.get().reject(error);
  198. }
  199. }
  200. startSession(options) {
  201. options = Object.assign({ explicit: true }, options);
  202. if (!this.topology) {
  203. throw new error_1.MongoNotConnectedError('MongoClient must be connected to start a session');
  204. }
  205. return this.topology.startSession(options, this.s.options);
  206. }
  207. withSession(optionsOrOperation, callback) {
  208. let options = optionsOrOperation;
  209. if (typeof optionsOrOperation === 'function') {
  210. callback = optionsOrOperation;
  211. options = { owner: Symbol() };
  212. }
  213. if (callback == null) {
  214. throw new error_1.MongoInvalidArgumentError('Missing required callback parameter');
  215. }
  216. const session = this.startSession(options);
  217. const Promise = promise_provider_1.PromiseProvider.get();
  218. let cleanupHandler = ((err, result, opts) => {
  219. // prevent multiple calls to cleanupHandler
  220. cleanupHandler = () => {
  221. // TODO(NODE-3483)
  222. throw new error_1.MongoRuntimeError('cleanupHandler was called too many times');
  223. };
  224. opts = Object.assign({ throw: true }, opts);
  225. session.endSession();
  226. if (err) {
  227. if (opts.throw)
  228. throw err;
  229. return Promise.reject(err);
  230. }
  231. });
  232. try {
  233. const result = callback(session);
  234. return Promise.resolve(result).then(result => cleanupHandler(undefined, result, undefined), err => cleanupHandler(err, null, { throw: true }));
  235. }
  236. catch (err) {
  237. return cleanupHandler(err, null, { throw: false });
  238. }
  239. }
  240. /**
  241. * Create a new Change Stream, watching for new changes (insertions, updates,
  242. * replacements, deletions, and invalidations) in this cluster. Will ignore all
  243. * changes to system collections, as well as the local, admin, and config databases.
  244. *
  245. * @param pipeline - An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
  246. * @param options - Optional settings for the command
  247. */
  248. watch(pipeline = [], options = {}) {
  249. // Allow optionally not specifying a pipeline
  250. if (!Array.isArray(pipeline)) {
  251. options = pipeline;
  252. pipeline = [];
  253. }
  254. return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options));
  255. }
  256. /** Return the mongo client logger */
  257. getLogger() {
  258. return this.s.logger;
  259. }
  260. }
  261. exports.MongoClient = MongoClient;
  262. //# sourceMappingURL=mongo_client.js.map