module Network.Wai.EventSource.EventStream (
ServerEvent(..),
eventToBuilder
) where
import Blaze.ByteString.Builder
import Blaze.ByteString.Builder.Char8
import Data.Monoid
data ServerEvent
= ServerEvent {
eventName :: Maybe Builder,
eventId :: Maybe Builder,
eventData :: [Builder]
}
| CommentEvent {
eventComment :: Builder
}
| RetryEvent {
eventRetry :: Int
}
| CloseEvent
nl :: Builder
nl = fromChar '\n'
nameField, idField, dataField, retryField, commentField :: Builder
nameField = fromString "event:"
idField = fromString "id:"
dataField = fromString "data:"
retryField = fromString "retry:"
commentField = fromChar ':'
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 (fromShow 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')