senchalabs / connect

Connect is a middleware layer for Node.js
MIT License
9.84k stars 1.09k forks source link

How use specific methods on one route? #1100

Closed ruslankonev closed 6 years ago

ruslankonev commented 6 years ago

Can I write the same way like in express - app.get or app.post instead global app.use(/route, cb) or write switcher inside callback?

dougwilson commented 6 years ago

Hi @ruslankonev this module's goal is pretty simple: just a framework to chain together middleware. You can always implement a middleware that composes another middleware with a method filter, for example:

function method (m, mw) {
  return (req, res, next) => {
    return req.method === m ? mw(req, res, next) : next()
  };
}

// later
app.use('/', method('GET', (req, res) => res.end('hi!')))

Another is that you can use already-existing middleware out there and compose it here. For example, the Express .get, etc. comes from the module "router" (https://github.com/pillarjs/router), which you can always compose into connect, for example:

var connect = require('connect')
var Router = require('router')

var app = connect()
var router = new Router()

app.use(router)

router.get('/', (req, res) => res.end('hello!'))

I hope this helps!