{-# LANGUAGE CPP #-}
module Network.Wai.EventSource.EventStream (
ServerEvent(..),
eventToBuilder
) where
import Data.ByteString.Builder
#if __GLASGOW_HASKELL__ < 710
import Data.Monoid
#endif
data ServerEvent
= ServerEvent {
eventName :: Maybe Builder,
eventId :: Maybe Builder,
eventData :: [Builder]
}
| CommentEvent {
eventComment :: Builder
}
| RetryEvent {
eventRetry :: Int
}
| CloseEvent
nl :: Builder
nl = char7 '\n'
nameField, idField, dataField, retryField, commentField :: Builder
nameField = string7 "event:"
idField = string7 "id:"
dataField = string7 "data:"
retryField = string7 "retry:"
commentField = char7 ':'
field :: Builder -> Builder -> Builder
field l b = l `mappend` b `mappend` nl
eventToBuilder :: ServerEvent -> Maybe Builder
eventToBuilder (CommentEvent txt) = Just $ field commentField txt
eventToBuilder (RetryEvent n) = Just $ field retryField (string8 . show $ n)
eventToBuilder (CloseEvent) = Nothing
eventToBuilder (ServerEvent n i d)= Just $
(name n $ evid i $ mconcat (map (field dataField) d)) `mappend` nl
where
name Nothing = id
name (Just n') = mappend (field nameField n')
evid Nothing = id
evid (Just i') = mappend (field idField i')