Tidy up messaging client
Extract middleware into functions