20

包括阅读器在内的数以万亿计的 monad 教程,当您阅读它时似乎一切都清楚了。但是当你真的需要写的时候,就另当别论了。

我从未使用过 Reader,只是在实践中从未使用过。因此,尽管我读过它,但我不知道该怎么做。

我需要在 Scotty 中实现一个简单的数据库连接池,以便每个操作都可以使用该池。池必须是“全局的”并且可以被所有操作函数访问。我读到这样做的方法是 Reader monad。如果还有其他方法请告诉我。

你能帮我看看如何正确使用阅读器吗?如果我用我自己的例子看看它是如何完成的,我可能会学得更快。

{-# LANGUAGE OverloadedStrings #-}

module DB where

import Data.Pool
import Database.MongoDB

-- Get data from config
ip = "127.0.0.1"
db = "index"

--Create the connection pool
pool :: IO (Pool Pipe)
pool = createPool (runIOE $ connect $ host ip) close 1 300 5

-- Run a database action with connection pool
run :: Action IO a -> IO (Either Failure a)
run act = flip withResource (\x -> access x master db act) =<< pool

所以上面的很简单。我想在每个 Scotty 操作中使用“运行”功能来访问数据库连接池。现在,问题是如何将它包装在 Reader monad 中以使其可供所有函数访问?我知道对于所有 Scotty 操作函数,“池”变量必须“像全局”。

谢谢你。

更新

我正在使用完整的代码片段更新问题。我将“池”变量传递到函数链的位置。如果有人可以展示如何更改它以使用 monad Reader 请。我不明白该怎么做。

{-# LANGUAGE OverloadedStrings #-}

module Main where

import Network.HTTP.Types
import Web.Scotty
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import Data.Text.Lazy.Internal
import Data.Monoid (mconcat)
import Data.Aeson (object, (.=), encode)
import Network.Wai.Middleware.Static
import Data.Pool
import Database.MongoDB
import Control.Monad.Trans (liftIO,lift)

main = do
  -- Create connection pool to be accessible by all action functions
  pool <- createPool (runIOE $ connect $ host "127.0.0.1") close 1 300 5
  scotty 3000 (basal pool)

basal :: Pool Pipe -> ScottyM ()
basal pool = do
  middleware $ staticPolicy (noDots >-> addBase "static")
  get "/json" (showJson pool)

showJson :: Pool Pipe -> ActionM ()
showJson pool = do
  let run act = withResource pool (\pipe -> access pipe master "index" act) 
  d <- lift $ run $ fetch (select [] "tables")
  let r = either (const []) id d
  text $ LT.pack $ show r

谢谢。

更新 2

我尝试按照下面建议的方式进行操作,但它不起作用。如果有人有任何想法,请。编译错误列表太长了,我什至不知道从哪里开始......

main = do
  pool <- createPool (runIOE $ connect $ host "127.0.0.1") close 1 300 5
  scotty 3000 $ runReaderT basal pool

basal :: ScottyT LT.Text (ReaderT (Pool Pipe) IO) ()
basal = do
  middleware $ staticPolicy (noDots >-> addBase "static")
  get "/json" $ showJson

showJson :: ActionT LT.Text (ReaderT (Pool Pipe) IO) ()
showJson = do
  p <- lift ask
  let rdb a = withResource p (\pipe -> access pipe master "index" a)
  j <- liftIO $ rdb $ fetch (select [] "tables")
  text $ LT.pack $ show j

更新 3

感谢cdk提供的想法,并感谢Ivan Meredith提供 scottyT 的建议。这个问题也有帮助:如何将 Reader monad 添加到 Scotty 的 monad 这是编译的版本。我希望它可以帮助某人并节省一些时间。

import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.Encoding as T
import           Data.Text.Lazy (Text)
import           Control.Monad.Reader
import           Web.Scotty.Trans
import           Data.Pool
import           Database.MongoDB

type ScottyD = ScottyT Text (ReaderT (Pool Pipe) IO)
type ActionD = ActionT Text (ReaderT (Pool Pipe) IO)

-- Get data from config
ip = "127.0.0.1"
db = "basal"

main = do
  pool <- createPool (runIOE $ connect $ host ip) close 1 300 5
  let read = \r -> runReaderT r pool
  scottyT 3000 read read basal

-- Application, meaddleware and routes
basal ::  ScottyD ()
basal = do
  get "/" shoot

-- Route action handlers
shoot ::  ActionD ()
shoot = do
  r <- rundb $ fetch $ select [] "computers"
  html $ T.pack $ show r

-- Database access shortcut
rundb :: Action IO a -> ActionD (Either Failure a)
rundb a = do
  pool <- lift ask
  liftIO $ withResource pool (\pipe -> access pipe master db a)
4

2 回答 2

8

我一直试图自己找出这个确切的问题。感谢关于这个 SO question 的提示,以及我提出的其他研究,这些对我有用。您缺少的关键位是使用scottyT

毫无疑问,有一种更漂亮的方式来编写 runDB,但我在 Haskell 方面没有太多经验,所以如果你能做得更好,请发布它。

type MCScottyM = ScottyT TL.Text (ReaderT (Pool Pipe) IO)
type MCActionM = ActionT TL.Text (ReaderT (Pool Pipe) IO)

main :: IO ()
main = do
  pool <- createPool (runIOE $ connect $ host "127.0.0.1") close 1 300 5  
  scottyT 3000 (f pool) (f pool) $ app
    where
      f = \p -> \r -> runReaderT r p

app :: MCScottyM ()
app = do
  middleware $ staticPolicy (noDots >-> addBase "public")
  get "/" $ do 
    p <- runDB dataSources 
    html $ TL.pack $ show p 

runDB :: Action IO a -> MCActionM (Either Failure a) 
runDB a = (lift ask) >>= (\p ->  liftIO $ withResource p (\pipe -> access pipe master "botland" a))

dataSources :: Action IO [Document]
dataSources = rest =<< find (select [] "datasources")

更新

我想这个更漂亮一些。

runDB :: Action IO a -> MCActionM (Either Failure a) 
runDB a = do
  p <- lift ask
  liftIO $ withResource p db
    where
       db pipe = access pipe master "botland" a
于 2014-04-21T04:15:30.567 回答
2

正如您所暗示的,使其可访问的方法是将您的计算包装在Readermonad 或更可能的ReaderT变压器中。所以你的run功能(略有改变)

run :: Pool Pipe -> Action IO a -> IO (Either Failure a)
run pool act =
    flip withResource (\x -> access x master db act) =<< pool

变成

run :: Action IO a -> ReaderT (Pool Pipe) IO (Either Failure a)
run act = do
    pool <- ask
    withResource pool (\x -> access x master db act)

环境中的计算ReaderT r m a可以访问r使用ask,并且ReaderT似乎凭空变出!实际上,ReaderTmonad 只是在Env整个计算过程中进行管道连接,而您不必担心它。

要运行ReaderT操作,请使用runReaderT :: ReaderT r m a -> r -> m a. 所以你调用runReaderT你的顶级scotty函数来提供Pool并且runReaderT将解包ReaderT环境并在基本 monad 中返回一个值。

例如,评估您的run功能

-- remember: run act :: ReaderT (Pool Pipe) IO (Either Failure a)
runReaderT (run act) pool

但您不想使用runReaderTon run,因为它可能是更大计算的一部分,也应该共享ReaderT环境。尽量避免runReaderT在“叶子”计算上使用,您通常应该在程序逻辑中尽可能高地调用它。

编辑Reader:和之间的区别在于ReaderTReader是一个单子,ReaderT而是一个单子转换器。也就是说,ReaderTReader行为添加到另一个 monad(或 monad 转换器堆栈)。如果您不熟悉 monad 转换器,我会推荐真实世界的 haskell-transformers

您已经showJson pool ~ ActionM ()并且想要添加一个Reader可以访问Pool Pipe. 在这种情况下,您实际上需要ActionTScottyT转换器,而不是ReaderT为了使用scotty包中的功能。

注意ActionM是 定义type ActionM = ActionT Text IO的,对于ScottyM.

我没有安装所有必要的库,所以这可能不会进行类型检查,但它应该给你正确的想法。

basal :: ScottyT Text (ReaderT (Pool Pipe) IO) ()
basal = do
    middleware $ staticPolicy (...)
    get "/json" showJson

showJson :: ActionT Text (ReaderT (Pool Pipe) IO) ()
showJson = do
    pool <- lift ask
    let run act = withResource pool (\p -> access p master "index act)
    d <- liftIO $ run $ fetch $ select [] "tables"
    text . TL.pack $ either (const "") show d
于 2014-03-28T04:55:29.537 回答