refactor db calls out of middleware