const fs = require('fs') const os = require('os') const debug = require('debug') const path = require('path') const EventEmitter = require('events').EventEmitter const { MongoClient } = require('mongodb') const Collection = require('./collection.js') const filePluginFile = require('../plugins/files/index.js') const Model = require('./model.js') const util = require('./util.js') let hasDefaultManager = false function Manager(uri, opts, parent) { /** * Constructs a new manager which contains a new MongoDB client * * @param {string|Array|Object} uri - MongoDB connection URI string / replica set, or reuse a MongoClient instance * @param {Object} opts - * {String} - the name of the database * {Boolean} - return a promise * * @return {Connection|Promise} * @link https://www.mongodb.com/docs/drivers/node/v7.6/quick-reference/ * @link https://mongodb.github.io/node-mongodb-native/ (all versions) */ const that = (!hasDefaultManager && parent) ? parent : this if (!opts) opts = {} if (!(this instanceof Manager)) return new Manager(uri, opts) if (uri == 'init') return // opts: timestamps if (typeof opts.defaultFields != 'undefined') throw Error('opts.defaultFields has been depreciated, use opts.timestamps') if (typeof opts.timestamps == 'undefined') opts.timestamps = true // opts: logLevel if (typeof opts.logLevel == 'undefined') opts.logLevel = 2 if (opts.imagePlugin) { // renamed in v5 throw new Error('Monastery: imagePlugin has been renamed to filePlugin, see the file plugin migration docs') } // opts: separate out monastery options const mongoOpts = Object.keys(opts || {}).reduce((acc, key) => { if (![ 'databaseName', 'defaultObjects', 'logLevel', 'filePlugin', 'limit', 'noDefaults', 'nullObjects', 'promise', 'timestamps', 'useMilliseconds', 'forJest', 'showConnectionInfo', ].includes(key)) { acc[key] = opts[key] } return acc }, /** @type {import('mongodb').MongoClientOptions} */ ({})) // Add properties that.uri = uri that.error = debug('monastery:error' + (opts.logLevel >= 1 ? '*' : '')) that.warn = debug('monastery:warn' + (opts.logLevel >= 2 ? '*' : '')) that.info = debug('monastery:info' + (opts.logLevel >= 3 ? '*' : '')) that.opts = opts that.beforeModel = [] that.collections = {} that._openQueue = [] that.emitter = new EventEmitter() that.forJest = opts.forJest || false that.showConnectionInfo = opts.showConnectionInfo || false // If there is no DEBUG= environment variable, we will need to force the debugs on (due to bug on debug@4.3.4) if (!debug.namespaces) { if (opts.logLevel >= 1) that.error.enabled = true if (opts.logLevel >= 2) that.warn.enabled = true if (opts.logLevel >= 3) that.info.enabled = true } // Create a new MongoDB Client if (!that.uri) { throw new Error('No monastery connection URI provided.') } else if (typeof that.uri == 'string' || Array.isArray(that.uri)) { that.uri = that.connectionString(that.uri, opts.databaseName) // Driver 7 loads `os` via dynamic import(), which fails in CJS vm sandboxes like Jest if (!mongoOpts.runtimeAdapters) mongoOpts.runtimeAdapters = { os } that.client = new MongoClient(that.uri, mongoOpts) } else if (util.isObject(that.uri)) { that.client = that.uri } else { throw new Error('Invalid monastery connection URI provided.') } // Listen to MongoDB events for (let eventName of ['close', 'error', 'timeout']) { that.client.on(eventName, (e) => that.emitter.emit(eventName, e)) } // Listen to custom open event that.emitter.on('open', () => { // wait for all the on('open') events to get called first setTimeout(() => { for (let item of that._openQueue) { item() } }) }) // Initiate any plugins if (opts.filePlugin) { filePluginFile.setup(that, util.isObject(opts.filePlugin) ? opts.filePlugin : {}) } // Update the parent manager with the new manager if (!hasDefaultManager && parent) hasDefaultManager = true if (opts.promise) return that.open() that.open() return that // return that since it may be a different context } Manager.prototype.manager = function(uri, opts) { return new Manager(uri, opts, this) } Manager.prototype.arrayWithSchema = function(array, schema) { array.schema = schema return array } Manager.prototype.close = async function() { /** * Close the database connection, gracefully */ const _close = async () => { this.emitter.emit(this._state = 'closing') await this.client.close() this.emitter.emit(this._state = 'close') } if (this._state == 'open') { return await _close() } else if (this._state == 'opening') { return new Promise((resolve) => { this._openQueue.push(() => _close().then(resolve)) }) } else if (this._state == 'close' || this._state == 'closing') { return } } Manager.prototype.rawCommand = function(...args) { /** * Run a raw MongoDB command */ return this.db.command(...args) } Manager.prototype.connectionString = function(uri, databaseName) { /** * get the connection string * @param {string|array} uri * @param {string} * @return {string} */ if (!uri) { throw Error('No connection URI provided.') } // uri: array, sort out the connection string if (util.isArray(uri)) { if (!databaseName) { for (var i=0, l=uri.length; i { if (!this.emitter) { reject(new Error('Emitter not found! This can happen if two seperate monastery packages are imported into the ' + 'same project. E.g. the first package initializes the manager, and the second package tries to use it.')) } this.emitter.on('error', (err) => { resolve(err) }) }).then((err) => { return fn(err) }) } Manager.prototype.onOpen = function(fn) { /** * Called when a successful MongoClient connection has been made. * @param {Function} fn * @return {Promise(manager)} */ return new Promise((resolve, reject) => { if (!this.emitter) { reject(new Error('Emitter not found! This can happen if two seperate monastery packages are imported into the ' + 'same project. E.g. the first package initializes the manager, and the second package tries to use it.')) } if (this._state == 'open') { resolve(this) } this.emitter.on('open', () => { resolve(this) }) this.emitter.on('error', (err) => { reject(err) }) }).then((err) => { // If `then` is not chained, the error will be thrown, detached! return fn(err) }) } Manager.prototype.open = async function() { /** * Connect to the database * @return {Promise(manager)} */ try { this.openTimestamp = Date.now() this._state = 'opening' this.db = this.client.db() await this.client.connect() // now optional since db().command() will auto-connect if (this.showConnectionInfo) console.info(`Connected to MongoDB in ${Date.now() - this.openTimestamp}ms`) this.emitter.emit(this._state = 'open', this) return this } catch (err) { this._state = 'closed' // Only emit the error if there are listeners, since it will throw an unhandled error if (this.emitter.listeners('error').length > 0) { this.emitter.emit('error', err) } if (this.opts.promise || this.emitter.listeners('error').length == 0) { throw new Error(err) } } } Manager.prototype.parseData = function(obj, parseBracketToDotNotation, parseDotNotation) { return util.parseData(obj, parseBracketToDotNotation, parseDotNotation) } Manager.prototype.formatDuplicateKeyError = function(model, err, alwaysReturnArray) { return util.formatDuplicateKeyError(model, err, alwaysReturnArray) } Manager.prototype.model = Model Manager.prototype.getSignedUrl = filePluginFile.getSignedUrl Manager.prototype._getSignedUrl = () => { throw new Error('monastery._getSignedUrl() has been moved to monastery.getSignedUrl()') } module.exports = Manager