Refactor into two middleware and a handler.