gridfs/GridFsUnit.js

/**
 * @module flitter-gridfs/GridFsUnit
 */

const Unit = require('libflitter/Unit')
const Mongo = require('mongodb')

const GridFile = require('./models/File.model')

/**
 * Adds the GridFS file model and functionality to the Flitter app.
 * @extends libflitter/Unit~Unit
 */
class GridFsUnit extends Unit {
    /**
     * Defines the services required by this unit.
     * @returns {Array<string>}
     */
    static get services() {
        return [...super.services, 'database', 'models']
    }

    /**
     * Initialize a native MongoDB connection and create a GridFS bucket.
     * Also, register the GridFS file model to the application. ("gridfs::file")
     * @param {libflitter/app/FlitterApp~FlitterApp} app - the Flitter application to be bootstrapped
     * @returns {Promise<void>}
     */
    async go(app){

        await new Promise((resolve, reject) => {
            Mongo.MongoClient.connect(this.database.connect_string, { useNewUrlParser: true }, (err, client) => {
                if ( err ) reject(err)
                else {
                    const db = client.db()

                    this.mongo_client = client
                    this.mongo_db = db
                    this.mongo_bucket = new Mongo.GridFSBucket(db)

                    resolve()
                }
            })
        })

        this.models.external_model(this, 'file', GridFile)
    }

    /**
     * Clean up the unit's resources. Closes the native MongoDB connection.
     * @param {module:libflitter/app/FlitterApp~FlitterApp} app - the current Flitter app
     * @returns {Promise<void>}
     */
    async cleanup(app){
        this.mongo_client.close()
    }

    /**
     * Get the name of the service provided by this unit.
     * @returns {string} - "gridfs"
     */
    static get name() {
        return "gridfs"
    }
}

module.exports = exports = GridFsUnit