trasherdk / hyper-express

High performance Node.js webserver with a simple-to-use API powered by uWebsockets.js under the hood.
MIT License
0 stars 0 forks source link

Snippet: Explaining hyper-express scoped middleware #11

Open trasherdk opened 2 years ago

trasherdk commented 2 years ago

So the way Routers work in HyperExpress is based on pattern hierarchy. There is no isolation of middlewares to just the routers they are initialized on as the Routers are meant to allow for modularity. You can however target a specific set of routes with a middleware by attaching the middleware itself with a pattern that defines it's scope. For example:

const server = new HyperExpress.Server();

server.use((request, response, next) => {
    // This is a global middleware as it was attached without any pattern to the server instance.
    next(); 
});

server.use('/api', (request, response, next) => {
    // This is a limited middleware in the sense that it will only run on routes that begin with the '/api' pattern
    // So for example, It would run on something like '/api/login'
    next();
});

const router = new HyperExpress.Router();

router.use((request, response, next) => {
    // This is a limited range middleware that will only run on routes that begin with the '/api' pattern
    // This is because this router is later attached to the root/server app with the '/api' pattern
    next();
});

router.get('/login', (request, response) => {
    // Some code here
});

// The router is attached to the server on the '/api' pattern meaning all routes/middlewares of the router will apply on /api/...
server.use('/api', router);

Source: https://github.com/kartikk221/hyper-express/pull/65#issuecomment-1107958234