romaricpascal / express-mount-files

Declare express routes by creating files at the path you want them to handle requests for
MIT License
3 stars 1 forks source link

Reset middlewares #2

Open Rysakov1986 opened 4 years ago

Rysakov1986 commented 4 years ago

Hello! Your package is very cool! But, please add the ability to reset middlewares in nested route.

Example: path: /api/auth routes.js // middlewares check jwt token

path: /api/auth/login reset.js // reset or reset and set new middlewares

Or: add routes.js options for reset or add middlewares.

Thanks!

romaricpascal commented 4 years ago

Cheers!

Indeed, there's a need to avoid applying middleware to all routes inside a folder.

I'm not quite sure if it should be the responsibility of the library, though, at least for now. I'd prefer leaving it to the middleware to decide they do not need to run for a specific route. For example, by wrapping them as such:

// /api/auth/routes.js or maybe /api/routes.js
module.exports = except('/api/auth/login', [checkJWTToken])

/**
 * Creates a middleware that runs the given list of `middlewares` 
 * (or single middleware) unless the request path matches the given `path`
 * @param path String 
 * @param middlewares Function|Array<Function>
 * @return Function
 */
function except(path, middlewares) {
    // Automatically wrap arrays of middlewares
    if (Array.isArray(middlewares)) {
        return middlewares.map(middleware => except(path, middleware))
    }

    return function(req,res,next) {
        // Implementation might be a bit naive here
        // update to suit your own needs
        if (req.path !== path) {
            return middlewares(req,res,next);
        }
        next();
    }
}

function checkJWTToken(req, res, next) {
    // ...
}

Guess there's a slight overhead as the check would happen for each middleware. Not sure if Express or a library provides an API that allows to combine multiple middlewares into one:

module.exports = except(path, group(mw1,mw2,mw3))