refactor to extract connection logic