Search code examples
javascriptnode.jsexpressmiddleware

Expressjs - Use middleware inside middleware


I would like to use a middleware for validating requests based on a raml file.
What my code looks like:

// require   
let resources = require('osprey-resources');
let errorHandler = require('request-error-handler');
let handler = require('osprey-method-handler');

// create express instance
let app = express();

// ramlObj obtained by raml2obj.parse(myPath).then()
let router = resources(ramlObj.resources,
    function (method, path) {

        // get the method type : get/post/etc
        let methodType = method.method.toUpperCase();

        // provide a function (controller) for this path
        return controllers.provideController(methodType, path);
    }
);

// osprey-router middelware , created by osprey-resources
app.use('/v1', router);

// error Handler middelware
app.use(errorHandler(responder, DEFAULT_LANGUAGE, customMessages));

// What I want:

// routes middelware
app.use('/v1', custom_middleware(method, methodType, path), router);

where custom_middleware use osprey-method-handler inside with all parameters I provided to him. I tried connect without success


Solution

  • For your example you need to use a partial function to allow req, res and next to be sent to your custom_middleware function.

    An example using lodash:

    // Route
    app.use('/v1', _.partialRight(custom_middleware, method, methodType, path), router);
    
    // Function
    custom_middleware(req, res, next, method, methodType, path) {
        ...
    }