orm/src/services/Connection.js

/**
 * @module flitter-orm/src/services/Connection
 */

const { Service } = require('flitter-di')
const { MongoClient } = require('mongodb')

/**
 * Service to manage and provide access to a MongoDB
 * connection used by the models.
 *
 * This service is compatible with flitter-di and must
 * be registered under the 'scaffold' name.
 *
 * @extends {module:flitter-di/src/Service~Service}
 */
class Connection extends Service {
    /**
     * The active MongoDB connection, if there is one.
     * @type {MongoClient}
     */
    _connection

    /**
     * The name of this service.
     * @returns {string}
     */
    static get name() { return 'scaffold' }

    /**
     * Open a connection to the MongoDB database defined by
     * the provided url. Stores that connection in this service.
     *
     * This must be called before models can access the database.
     *
     * @param {string} url - the MongoDb connect url
     * @returns {Promise<mongodb/Connection>}
     */
    async open(url) {
        return new Promise((resolve, reject) => {
            MongoClient.connect(url, {
                useUnifiedTopology: true
            }, (err, connection) => {
                if ( err ) reject(err)
                else {
                    this._connection = connection
                    resolve(connection)
                }
            })
        })
    }

    /**
     * Close the connection to MongoDB.
     */
    async close() {
        await this._connection.close()
    }

    /**
     * From the open connection, fetch a collection with the specified name.
     * @param {string} name
     * @returns {Collection}
     */
    collection(name) {
        return this._connection.db().collection(name)
    }
}

module.exports = exports = Connection