Last active
May 6, 2019 12:06
-
-
Save evilUrge/0833d55730e1ac5f6b0df4a4b0a7e1b0 to your computer and use it in GitHub Desktop.
Express.js\restify auto register handlers by path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = (() => { | |
/** | |
* Map all available handlers to express route. | |
* @type {{handler}|*} | |
*/ | |
const fs = require('fs'); | |
const express = require('express'); | |
const bodyParser = require('body-parser'); | |
const bunyan = require('bunyan'); | |
const logger = bunyan.createLogger({name: 'example', level: process.env.NODE_ENV ? 'debug' : 'error'}); | |
const server = express({ | |
name: 'example express server', | |
log: logger, | |
}); | |
const router = express.Router(); | |
const baseHandlersFolder = '../src/handlers'; | |
fs.readdirSync(baseHandlersFolder).forEach((fileName) => { | |
if (fileName.includes('.js')) { | |
const HandlerImport = require(`${baseHandlersFolder}/${fileName}`); | |
Object.keys(HandlerImport).forEach((handler) => { | |
try { | |
const methods = [handler].type ? HandlerImport[handler].type : ['get']; | |
(Array.isArray(methods) ? methods : [methods]).forEach((method) => | |
router[method ? method : 'get'](`${handler === 'all' ? '*' : '/' + handler}${HandlerImport[handler].url ? HandlerImport[handler].url : ''}`, HandlerImport[handler].exec ? HandlerImport[handler].exec : HandlerImport[handler])); | |
logger.info(handler === 'all' ? '*' : '/' + handler) | |
} catch (e) { | |
console.error(e); | |
logger.error(`Failed to register the following handler: ${handler}`); | |
} | |
}) | |
} | |
}); | |
return server | |
.use(bodyParser.json()) | |
.use(bodyParser.urlencoded({extended: true})) | |
.use(router); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example for a handler func