tie/Response.template.hs

32 lines
905 B
Haskell
Raw Normal View History

2022-06-12 23:55:51 +03:00
module Tie.Template.Response_
( ToResponse (..),
2022-12-20 11:19:42 +03:00
-- * NDJSON support
NDJSON,
responseNDJSON,
2022-06-12 23:55:51 +03:00
)
where
2022-12-20 11:19:42 +03:00
import qualified Data.Aeson
import qualified Data.Aeson.Encoding
import qualified Data.ByteString.Builder
import qualified Network.HTTP.Types
2022-06-12 23:55:51 +03:00
import qualified Network.Wai
2022-12-20 11:19:42 +03:00
type NDJSON element = ((element -> IO ()) -> IO () -> IO ())
responseNDJSON :: (Data.Aeson.ToJSON element) => Network.HTTP.Types.Status -> Network.HTTP.Types.ResponseHeaders -> NDJSON element -> Network.Wai.Response
2022-12-20 11:19:42 +03:00
responseNDJSON status responseHeaders stream =
Network.Wai.responseStream status responseHeaders $ \emit flush ->
stream
( \element ->
emit
( Data.Aeson.Encoding.fromEncoding (Data.Aeson.toEncoding element)
<> Data.ByteString.Builder.char7 '\n'
)
)
flush
2022-06-12 23:55:51 +03:00
class ToResponse a where
toResponse :: a -> Network.Wai.Response