{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE LambdaCase #-}
module Miso.Subscription.SSE
(
sseSub
, SSE (..)
) where
import Control.Monad.IO.Class
import Data.Aeson
import Miso.Effect (Sub)
import Miso.FFI
import Miso.String
import qualified Miso.FFI.SSE as SSE
sseSub :: FromJSON msg => MisoString -> (SSE msg -> action) -> Sub action
sseSub url f = \sink -> do
es <- SSE.new url
SSE.addEventListener es "message" $ \val -> do
dat <- parse =<< SSE.data' val
(liftIO . sink) (f (SSEMessage dat))
SSE.addEventListener es "error" $ \_ ->
(liftIO . sink) (f SSEError)
SSE.addEventListener es "close" $ \_ ->
(liftIO . sink) (f SSEClose)
data SSE message
= SSEMessage message
| SSEClose
| SSEError
deriving (Show, Eq)