需要 运行 MonadHandler 但 Return STM

Need to Run MonadHandler but Return STM

我正在尝试在 websocket 请求中执行数据库查询。这是对 this 示例的改编。

为此,我尝试创建一个专门的 race_ - 它也将具有我将用于查询数据库的 MonadHandler。这导致以下非工作代码:

    handlerRace_
        (forever $ atomically (readTChan readChan) >>= sendTextData)
        (sourceWS $$ mapM_C (\msg -> atomically $ do
            users <- lift (runDB $ selectList [] [] :: Handler [Entity User]) -- query the DB
            writeTChan writeChan $ msg
        ))

handlerRace_ ::  (MonadBaseControl IO m, MonadHandler m) => m a -> m b -> m ()
handlerRace_ = race_

和错误:

Couldn't match type ‘t0 (HandlerT App IO)’ with ‘STM’
Expected type: STM [Entity User]
  Actual type: t0 (HandlerT App IO) [Entity User]
In a stmt of a 'do' block:
  users <- lift (runDB $ selectList [] [] :: Handler [Entity User])

也许我遗漏了一些东西(示例代码不完整),但为什么不把 atomically 放在 writeTChan 上,因为这将是使用 STM 的目的(未经测试):

handlerRace_
    (forever $ atomically (readTChan readChan) >>= sendTextData)
    (sourceWS $$ mapM_C (\msg -> do
        users <- lift (runDB $ selectList [] [] :: Handler [Entity User]) -- query the DB
        atomically $ writeTChan writeChan msg
    ))