Skip to content

Latest commit

 

History

History
29 lines (26 loc) · 1.39 KB

Middlewares.md

File metadata and controls

29 lines (26 loc) · 1.39 KB

Middlewares

HyperExpress follows the standard format of middlewares and implements similar API to ExpressJS. This allows for full compatibility with most existing ExpressJS middlewares while maintaining high performance.

How To Use

Middlewares support both callback and promise based iteration similar to ExpressJS. Throwing or iterating next with an Error object will trigger the global error handler.

Callback-Based Iteration

// Binds a midddleware that will run on all routes that begin with '/api' in this router.
router.use('/api', (request, response, next) => {
    some_async_operation(request, response)
    .then(() => next()) // Calling next() will trigger iteration to the next middleware
    .catch((error) => next(error)) // passing an Error as a parameter will automatically trigger global error handler
});

Async/Promise-Based Iteration

// Binds a global middleware that will run on all routes.
server.use(async (request, response) => {
    // You can also just return new Promise((resolve, reject) => {}); instead of async callback
    try {
        await some_async_operation(request, response);
    } catch (error) {
        return error; // This will trigger global error handler as we are returning an Error
    }
});