Optimization and code clarification.
Added mock as requirement.
Added (somewhat complex) unit tests to validate the middleware.