refactor common query-response code