chain-able-server
Version:
chainable server running with as-needed middleware
110 lines (98 loc) • 2.64 kB
JavaScript
const log = require('fliplog')
const toarr = require('to-arr')
const express = require('express')
const ChainedMap = require('chain-able/ChainedMapExtendable')
const middlewareFactories = require('./middleware')
class Server extends ChainedMap {
/**
* @alias create
* @return {Server} @chainable
*/
static init() {
return new Server().create()
}
static create() {
return new Server().create()
}
/**
* @desc adds express app
* @modifies .app
* @return {Server} @chainable
*/
create() {
this.app = express()
return this
}
/**
* @TODO fliphub would make more sense, or could use this in fliphub
*
* @desc factory, when doing `servers`!
* require call use
*
* @param {string} name
* @param {Object | null} [args=null] e.g., webpack config
* @param {Object | null} [options=null] specific middleware options
* @return {Server} @chainable
*/
use(name, args = null, options = {}) {
if (typeof name !== 'string') {
log.verbose(1).green('using custom middleware').echo(this.get('debug'))
return this.middleware(name)
}
const fn = middlewareFactories[name]
log
.verbose(1)
.data({args, options})
.green('using server middleware: ' + name)
.echo(this.get('debug') || true)
return this.middleware(args ? fn(args, options) : fn)
}
/**
* @todo {string | Array<string>} middleware
* @param {Function | Array<Function>} middlewares express middleware
* @return {Server} @chainable
*/
middleware(middlewares) {
toarr(middlewares).forEach(middleware => this.app.use(middleware))
return this
}
/**
* @TODO first open port
* @desc starts listening on port, runs apps
* @param {number} [port=null] optional port override
* @return {Server} @chainable
*/
listen(port = null) {
const app = this.app
// link for logging
port = port || app.get('port') || 3000
const link = 'http://localhost:' + port
// start
app.listen(port, error => {
if (error) log.catch(error)
log.addSpinner(link, link)
log.startSpinners([
'🤾 ',
'🤾 ',
'∞🤾 ',
'∞🤾 ',
' ∞🤾 ',
' ∞🤾 ',
' ∞🤾∞ ',
' ∞🤾∞ ',
' ∞∞🤾 ',
' ∞🤾 ',
' ∞🤾 ',
' ∞∞🤾 ',
' ∞🤾∞ ',
' ∞🤾∞ ',
' 🤾∞∞ ',
' 🤾∞∞ ',
'🤾∞ ',
'🤾∞ ',
])
})
return this
}
}
module.exports = Server