refactor discovery middleware