factored out cache middleware