Skip to content

Instantly share code, notes, and snippets.

@evilUrge
Last active May 6, 2019
Embed
What would you like to do?
Express.js\restify auto register handlers by path
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);
})();
@evilUrge

This comment has been minimized.

Copy link
Owner Author

@evilUrge evilUrge commented Jan 15, 2019

Example for a handler func

exports.demo = {type: ['get', 'post'], exec: (req, res) => {
    if (req.body) {
        res.status(200).send('do something with post')
    } else if(req.query.url){
        res.status(200).send('do something with get')
    } else {
        return res.status(400).send(`don't do anything at all`).end();
    }
}};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment