Skip to content

Commit

Permalink
minor: Remove module & init calls with context as this
Browse files Browse the repository at this point in the history
  • Loading branch information
Atinux committed Oct 20, 2017
1 parent 5c59d3d commit e958052
Show file tree
Hide file tree
Showing 8 changed files with 46 additions and 833 deletions.
8 changes: 4 additions & 4 deletions lib/acl.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ const { join } = require('path')

const glob = require('glob-promise')

module.exports = async function (srcDir) {
module.exports = async function (srcDir, { conf, log }) {
// Add mono modules (conf.mono.modules) to aclFiles
this.conf.mono.modules.forEach(({ name, path }) => {
conf.mono.modules.forEach(({ name, path }) => {
path = join(path, 'acl.js')
try {
require(path)
this.log.debug(`ACL loaded from ${name} module`)
log.debug(`ACL loaded from ${name} module`)
} catch (err) {
// Do nothing
}
Expand All @@ -26,6 +26,6 @@ module.exports = async function (srcDir) {
// name is like users/users.init.js
const path = join(srcDir, name)
require(path)
this.log.debug(`ACL loaded from ${name}`)
log.debug(`ACL loaded from ${name}`)
})
}
20 changes: 10 additions & 10 deletions lib/conf.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ function customizer(objValue, srcValue) {
if (isObject(objValue) || isObject(srcValue)) return mergeWith(objValue, srcValue, customizer)
}

function defaultOptions(conf) {
function defaultOptions(conf, { appDir, dir }) {
conf.mono = conf.mono || {}

// Modules options
Expand All @@ -19,10 +19,10 @@ function defaultOptions(conf) {
let name
// If path is not an absolute path but a node module
if (['.', '/'].indexOf(path[0]) === -1) {
path = join(this.appDir, 'node_modules', path)
path = join(appDir, 'node_modules', path)
}
// If relative path, make it absolute from dir
if (path[0] === '.') path = join(this.dir, path)
if (path[0] === '.') path = join(dir, path)
// Make sure path ends by /
if (path.slice(-1) !== '/') path += '/'
// If the package.json is present
Expand Down Expand Up @@ -52,10 +52,10 @@ function defaultOptions(conf) {
return conf
}

module.exports = function (dir) {
module.exports = function (dir, { log, pkg, appDir }) {
// Environement
const env = process.env.NODE_ENV || 'development'
this.log.debug(`Environment: ${env}`)
log.debug(`Environment: ${env}`)

// Conf path
const confPath = process.env.MONO_CONF_PATH || join(dir, 'conf')
Expand Down Expand Up @@ -87,24 +87,24 @@ module.exports = function (dir) {
// Ignore for local.js file
if (filename === 'local') return
// Log an error for others
return this.log.warn(`Could not load config file: conf/${filename}.js`)
return log.warn(`Could not load config file: conf/${filename}.js`)
}

// Load its source
this.log.debug(`Loading conf/${filename}.js configuration`)
log.debug(`Loading conf/${filename}.js configuration`)
sources.push(source)
})

// Add env, name & version to the returned config
sources.push({
env,
name: this.pkg.name,
version: this.pkg.version
name: pkg.name,
version: pkg.version
})

// Merged sources with conf
const conf = mergeWith.apply(null, [...sources, customizer])

// Return conf
return defaultOptions.call({ appDir: this.appDir, dir }, conf)
return defaultOptions(conf, { appDir, dir })
}
7 changes: 4 additions & 3 deletions lib/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ const morgan = require('morgan')
const helmet = require('helmet')
const bodyParser = require('body-parser')

module.exports = async function (httpOptions) {
module.exports = async function ({ conf, log }) {
const httpOptions = conf.mono.http
// Default options
const port = httpOptions.port = parseInt(process.env.PORT, 10) || httpOptions.port || 8000
httpOptions.logLevel = (typeof httpOptions.logLevel !== 'undefined' ? httpOptions.logLevel : 'dev')
Expand Down Expand Up @@ -35,7 +36,7 @@ module.exports = async function (httpOptions) {
const onListening = () => {
const { address, port } = server.address()
const host = (['0.0.0.0', '127.0.0.1'].includes(address) ? 'localhost' : address)
this.log.debug('Server running on ' + chalk.underline(`http://${host}:${port}`))
log.debug('Server running on ' + chalk.underline(`http://${host}:${port}`))
}
// Listen method
const listen = () => {
Expand All @@ -56,7 +57,7 @@ module.exports = async function (httpOptions) {
if (httpOptions.bodyParser.json !== false) app.use(bodyParser.json(httpOptions.bodyParser.json))
// Logger middleware
if (typeof httpOptions.logLevel === 'string') {
app.use(morgan(httpOptions.logLevel, { stream: this.log.stream }))
app.use(morgan(httpOptions.logLevel, { stream: log.stream }))
}
// Return app & server
return { app, server, listen }
Expand Down
24 changes: 14 additions & 10 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@ try {
throw new Error(`[mono] Could not find package.json in application directory ${appDir}`)
}

async function bootMonoModules(modules) {
async function bootMonoModules(context) {
const { conf, log } = context
const modules = conf.mono.modules

// Boot each modules in series
for (const { name, path } of modules) {
let module
Expand All @@ -44,8 +47,8 @@ async function bootMonoModules(modules) {
if (typeof module !== 'function') return

// Load module and log it
this.log.debug(`Boot ${name} module`)
await module.call(this)
log.debug(`Boot ${name} module`)
await module(Object.assign({}, context, { log: log.module(name) }))
}
}

Expand All @@ -61,36 +64,37 @@ module.exports = async function (dir) {
process.on('unhandledRejection', handleThrow)

// Load configuration
const conf = module.exports.conf = loadConf.call({ log: module.exports.log, pkg, appDir }, dir)
const conf = module.exports.conf = loadConf(dir, { log: module.exports.log, pkg, appDir })

// Load logs
const log = module.exports.log = new MonoLog(conf.name, conf.mono.log)
log.profile('Startup')

// Create HTTP server
const { app, server, listen } = await httpServer.call({ log }, conf.mono.http)
const { app, server, listen } = await httpServer({ conf, log })

const context = { log, conf, app, server }
// Boot mono modules
await bootMonoModules.call({ log, conf, appDir, server }, conf.mono.modules)
await bootMonoModules(context)

// Add JWT middleware (add req.generateJWT & req.loadSession)
initJWT(conf.mono.jwt)

// Init every modules
await initModules.call({ log, conf, appDir, pkg }, srcDir, { app, server })
await initModules(srcDir, context)

// Load ACL
await loadACL.call({ log, conf, appDir, pkg }, srcDir)
await loadACL(srcDir, context)

// Load routes
await loadRoutes.call({ log, conf, appDir }, srcDir, app)
await loadRoutes(srcDir, context)

// Make the server listen
if (!conf.mono.http.preventListen) await listen()
log.profile('Startup')

// Return app & server
return { conf, app, server }
return context
}

module.exports.log = new MonoLog(pkg.name || 'mono')
Expand Down
11 changes: 6 additions & 5 deletions lib/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ const { join } = require('path')

const glob = require('glob-promise')

module.exports = async function (srcDir, { app, server }) {
module.exports = async function (srcDir, context) {
const { conf, log } = context
let initFiles = []

// Add mono modules (conf.mono.modules) to initFiles
this.conf.mono.modules.forEach(({ name, path }) => {
conf.mono.modules.forEach(({ name, path }) => {
path = join(path, 'init.js')
try {
require(path)
Expand Down Expand Up @@ -34,17 +35,17 @@ module.exports = async function (srcDir, { app, server }) {
const initPromises = initFiles.map(async ({ isModule, name, path}) => {
// If mono module
if (isModule) {
this.log.debug(`Init ${name} module`)
log.debug(`Init ${name} module`)
} else {
this.log.debug(`Init ${name}`)
log.debug(`Init ${name}`)
}

// Require module
let module = require(path)

// Load module and wait for it to be initialized
if (typeof module === 'function') {
await module.call(this, { app, server, conf: this.conf, log: this.log.module(name) })
await module(Object.assign({}, context, { log: log.module(name) }))
}
})

Expand Down
9 changes: 4 additions & 5 deletions lib/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,13 @@ validate.options({
allowUnknownCookies: true
})

module.exports = async function (srcDir, app) {
const log = this.log
module.exports = async function (srcDir, { conf, log, app }) {
let routes = []
let routeFiles = []

// Send back its name for discovery
app.get('/_', (req, res) => {
res.status(200).send(this.conf.name)
res.status(200).send(conf.name)
})

// Monitoring route
Expand All @@ -36,7 +35,7 @@ module.exports = async function (srcDir, app) {
})

app.get('/_version', (req, res) => {
res.status(200).send(this.conf.version)
res.status(200).send(conf.version)
})

// List all routes
Expand All @@ -45,7 +44,7 @@ module.exports = async function (srcDir, app) {
})

// Add mono modules (conf.mono.modules) to routeFiles
this.conf.mono.modules.forEach(({ name, path }) => {
conf.mono.modules.forEach(({ name, path }) => {
path = join(path, 'routes.js')
try {
require(path)
Expand Down

0 comments on commit e958052

Please sign in to comment.