Refactoring serve and adding unit tests for it