{-# 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 {
ServerEvent -> Maybe Builder
eventName :: Maybe Builder,
ServerEvent -> Maybe Builder
eventId :: Maybe Builder,
ServerEvent -> [Builder]
eventData :: [Builder]
}
| {
:: Builder
}
| RetryEvent {
ServerEvent -> Int
eventRetry :: Int
}
| CloseEvent
nl :: Builder
nl :: Builder
nl = Char -> Builder
char7 Char
'\n'
nameField, idField, dataField, retryField, commentField :: Builder
nameField :: Builder
nameField = String -> Builder
string7 String
"event:"
idField :: Builder
idField = String -> Builder
string7 String
"id:"
dataField :: Builder
dataField = String -> Builder
string7 String
"data:"
retryField :: Builder
retryField = String -> Builder
string7 String
"retry:"
= Char -> Builder
char7 Char
':'
field :: Builder -> Builder -> Builder
field :: Builder -> Builder -> Builder
field Builder
l Builder
b = Builder
l forall a. Monoid a => a -> a -> a
`mappend` Builder
b forall a. Monoid a => a -> a -> a
`mappend` Builder
nl
eventToBuilder :: ServerEvent -> Maybe Builder
eventToBuilder :: ServerEvent -> Maybe Builder
eventToBuilder (CommentEvent Builder
txt) = forall a. a -> Maybe a
Just forall a b. (a -> b) -> a -> b
$ Builder -> Builder -> Builder
field Builder
commentField Builder
txt
eventToBuilder (RetryEvent Int
n) = forall a. a -> Maybe a
Just forall a b. (a -> b) -> a -> b
$ Builder -> Builder -> Builder
field Builder
retryField (String -> Builder
string8 forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. Show a => a -> String
show forall a b. (a -> b) -> a -> b
$ Int
n)
eventToBuilder (ServerEvent
CloseEvent) = forall a. Maybe a
Nothing
eventToBuilder (ServerEvent Maybe Builder
n Maybe Builder
i [Builder]
d)= forall a. a -> Maybe a
Just forall a b. (a -> b) -> a -> b
$
Maybe Builder -> Builder -> Builder
name Maybe Builder
n (Maybe Builder -> Builder -> Builder
evid Maybe Builder
i forall a b. (a -> b) -> a -> b
$ forall a. Monoid a => [a] -> a
mconcat (forall a b. (a -> b) -> [a] -> [b]
map (Builder -> Builder -> Builder
field Builder
dataField) [Builder]
d)) forall a. Monoid a => a -> a -> a
`mappend` Builder
nl
where
name :: Maybe Builder -> Builder -> Builder
name Maybe Builder
Nothing = forall a. a -> a
id
name (Just Builder
n') = forall a. Monoid a => a -> a -> a
mappend (Builder -> Builder -> Builder
field Builder
nameField Builder
n')
evid :: Maybe Builder -> Builder -> Builder
evid Maybe Builder
Nothing = forall a. a -> a
id
evid (Just Builder
i') = forall a. Monoid a => a -> a -> a
mappend (Builder -> Builder -> Builder
field Builder
idField Builder
i')