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} [migrations_dir = './flaps.json'] - Path to the directory used to track applied migrations. This directory may not exist yet.
     */
    constructor(migrations_dir = './flaps'){
        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.dir = path.resolve(migrations_dir)
    }

    /**
     * Get the name of service provided by this unit: 'flap'
     * @returns {string} "flap"
     */
    static get 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
     * @returns {Promise<void>}
     */
    async go(app){
        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()
            }
        }

        this.loaded_migrations = migrations

        const flapper = require('./FlapHelper')(false)
        await flapper.mkdir(this.dir)
    }

    /**
     * Get an array with the directive classes provided by this unit.
     * @returns {Array<module:flitter-cli/Directive~Directive>}
     */
    directives(){
        return [
            FlapDirective
        ]
    }

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

    /**
     * Get the directories managed by this unit.
     * @returns {Object}
     */
    directories() {
        return {
            flaps: this.dir
        }
    }

}

module.exports = exports = FlapUnit