Refactor connect func