Skip to content

Commit

Permalink
feat(controllers): generate controllers map including sub-dir
Browse files Browse the repository at this point in the history
  • Loading branch information
greenhat616 committed Aug 4, 2020
1 parent 4b974d7 commit 97a99aa
Showing 1 changed file with 35 additions and 5 deletions.
40 changes: 35 additions & 5 deletions src/controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,40 @@ const winston = require('winston')
const colors = require('colors/safe')
const path = require('path')

function readDir (dir) {
const files = fs.readdirSync(dir)
if (files.length <= 0) return
const map = {}
for (const file of files) {
const filePath = path.join(dir, file)
const stat = fs.statSync(filePath)
if (stat.isDirectory()) {
const subDirMaps = readDir(filePath)
if (subDirMaps && subDirMaps.length > 0) {
map[file] = map[file]
? Object.assign(
map[file],
subDirMaps
)
: subDirMaps
}
} else {
map[file.substring(0, file.length - 3)] = map[file.substring(0, file.length - 3)]
? Object.assign(
map[file.substring(0, file.length - 3)],
require(filePath)
)
: require(filePath)
}
}
return map
}

function genControllersMap () {
const dir = path.join(__dirname, './controllers')
return readDir(dir)
}

class controllers {
constructor (controller) {
if (controller) {
Expand All @@ -28,11 +62,7 @@ class controllers {
async load () {
try {
// Load Controller
const controllers = {}
const dir = fs.readdirSync(path.join(__dirname, '../', './src/controllers'))
await dir.map((item, index, input) => {
controllers[item.substring(0, item.length - 3)] = module.parent.require(path.join(__dirname, '../', './src/controllers/' + item))
})
const controllers = genControllersMap()
return controllers
} catch (e) {
winston.error(colors.red(e))
Expand Down

0 comments on commit 97a99aa

Please sign in to comment.