Refactoring middleware