BSD-3-Clause licensed
Maintained by Athan Clark
This version can be pinned in stack with:websockets-simple-0.2.0@sha256:aadc52e93864fedf5e963e2915ea50b9769017141d5f13aef362b94199a65319,1971

Module documentation for 0.2.0

websockets-simple

Provides for a slightly more composable structure for websocket apps:

data Input = Increment | Decrement
  deriving (FromJSON)

data Output = Value Int
  deriving (ToJSON)

myApp :: MonadBaseControl IO m => m (WebSocketsApp m Input Output)
myApp = do
  countRef <- liftIO $ newIORef 0
  emitter <- liftIO $ newIORef (Nothing :: Async ())

  let killEmitter = do
        mThread <- liftIO $ readIORef emitter
        case mThread of
          Nothing -> pure ()
          Just thread -> cancel thread

  pure WebSocketsApp
    { onOpen = \WebSocketsAppParams{send} ->
        liftBaseWith $ \runInBase -> do
          thread <- async $ forever $ do
            count <- readIORef countRef
            runInBase $ send $ Value count
            threadDelay 1000000 -- every second, emit the current value
          writeIORef emitter (Just thread)
    , onReceive = \WebSocketsAppParams{send,close} x -> do
        count <- liftIO $
          ( modifyIORef countRef $ case x of
              Increment -> (+ 1)
              Decrement -> (-) 1
          ) *> readIORef countRef
        if count >= 10 || count <= -10
          then close
          else send (Value count)
    , onClose = \mReason -> do
        killEmitter
        case mReason of
          Nothing -> liftIO $ writeIORef countRef 0
          Just _ -> pure ()
    }