Refactored into a middleware + fixed tests