Refactor to reduce the number of statements in _middleware

The build failed because the _middleware function has too many statements