flap/FlapUnit.js

/**
 * @module flitter-flap/FlapUnit
 */

const Unit = require('libflitter/Unit')
const FlapDirective = require('./directives/FlapDirective')
const path = require('path')

/**
 * Unit providing functionality for flitter-flap.
 * @extends module:libflitter/Unit~Unit
 */
class FlapUnit extends Unit {

    /**
     * Initializes the class. 
     * Resolves the path to the migration tracking file.
     * @param {string} [migration_file = './flaps.json'] - Path to the file used to track applied migrations. This file may not exist yet. Must end in '.json'.
     */
    constructor(migration_file = './flaps.json'){
        super()

        /**
         * Fully-qualified path to the file used to track applied migrations.
         * This file may not necessarily exist yet, but its directory must.
         * This file must end in the '.json' extension.
         * @name FlapUnit#file
         * @type {string}
         */
        this.file = path.resolve(migration_file)
    }

    /**
     * Get the name of the unit.
     * @returns {string} "flap"
     */
    name(){
        return "flap"
    }

    /**
     * Loads the unit.
     * Checks each unit. If the unit has a migrations() function, call it to get the path to the unit's migration folder.
     * Binds the array of folders, path to the migration tracking file, and helper functions to the context.
     * @param {module:libflitter/app/FlitterApp~FlitterApp} app
     * @param {module:libflitter/Context~Context} context
     * @returns {Promise<void>}
     */
    async go(app, context){
        let migrations = {}
        
        for ( let unit_name in app.units ){
            const unit = app.units[unit_name]
            
            if ( typeof unit.migrations === 'function' ){
                migrations[unit.name()] = unit.migrations()
            }
        }
        
        context.bind('migrations', migrations)
        context.bind('file', this.file)
        context.bind('helper', require('./FlapHelper'))
    }

    /**
     * Get an array with the directive classes provided by this unit.
     * 
     * @returns {Directive[]}
     */
    directives(){
        return [
            FlapDirective
        ]
    }

    /**
     * Get the fully-qualified path to this unit's migration files.
     * @returns {string}
     */
    migrations(){
        return path.resolve(__dirname, "migrations")
    }
    
}

module.exports = exports = FlapUnit