refactor caching middleware