ernesto petit
ernesto petit

Reputation: 1627

many functions in one middleware expressjs restful api

I have a doubt about middelware in express.

I want to many thinks in one middleware. For example

I have this code y me middleware

module.exports = function(req,res,next) {
    if(req.method === 'GET') {
        res.end('GET method not supported');
    } else {
        next();
    }
}; 

and I use it like this

app.route('/', <the_middleware>, (res, req, next) => {
 // Code
})

But I am wondering if is possible to do something like this

app.route('/', <the_middleware>.<the function1>, (res, req, next) => {
     // Code
    })

app.route('/', <the_middleware>.<the_function2>, (res, req, next) => {
     // Code
    })

is there a possiblitity to do something like

 function function1 (req,res,next) {
        if(req.method === 'GET') {
            res.end('GET method not supported');
        } else {
            next();
        }
    }; 

 function function2 (req,res,next) {
        if(req.method === 'GET') {
            res.end('GET method not supported');
        } else {
            next();
        }
    }; 

module.exports = <I don`t know what go here>

Thanks.

Update. IT works, my code now is

The router

router.post('/', checkAuth.sayHi, checkAuth.sayBye, (req, res, next) => {

    console.log('good');
    res.status(200).send('it works');
    console.log('yes');

});

The middleware

module.exports = {

    sayHi(req, res, next) {
        console.log('hi');
        next();

    },

    sayBye(req, res, next) {
        console.log('bye')
        next();
    }
};

Upvotes: 0

Views: 49

Answers (1)

Steve Holgado
Steve Holgado

Reputation: 12089

You can just export an object containing both functions:

module.exports = {
  function1,
  function2
}

Upvotes: 1

Related Questions