libflitter/app/AppUnit.js

/**
 * @module libflitter/app/AppUnit
 */

const Unit = require('../Unit')

/**
 * The app unit is the final unit in the stack, and makes the final call
 * to the Express HTTP server. As such, it is the innermost context which
 * the Flutter application can access. No other units after this will show
 * up to the Flutter components.
 *
 * @extends module:libflitter/Unit~Unit
 */
class AppUnit extends Unit {

    /**
     * Loads the unit. Launches the HTTP server.
     * @param {module:libflitter/app/FlitterApp~FlitterApp} app - the Flitter app
     * @returns {Promise<void>}
     */
    async go(app){
        
        await this.serve_express(app)
        
    }

    /**
     * Launch an HTTP server from the underlying Express app on the port configured by the config value "server.port".
     * @param {module:libflitter/app/FlitterApp~FlitterApp} app - the Flitter app to be served
     * @returns {Promise<any>}
     */
    serve_express(app){
        const port = app.d.config.get('server.port')
        
        return new Promise(
            (resolve, reject) => {
                app.express.listen(port, (error) => {
                    if (error) reject(error)
                    
                    app.d.utility.log(`Flitter running on port ${port}! Press ^C to exit cleanly.`)

                    process.on('SIGTERM', async () => {
                        console.log("\nStopping Flitter...")
                        await app.stop()
                        resolve()
                    })

                    process.on('SIGINT', async () => {
                        console.log("\nStopping Flitter...")
                        await app.stop()
                        resolve()
                    })
                })
            }
        )
    }

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

module.exports = AppUnit