适用于每个处理器读取器的Scotty Monad变压器 [英] Scotty monad transformer for per-handler Reader

查看:88
本文介绍了适用于每个处理器读取器的Scotty Monad变压器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题 Web,Scotty:连接池作为monad读取器显示了如何使用ScottyTReader monad嵌入堆栈中以访问静态配置(在这种情况下为连接池).

In the question Web, Scotty: connection pool as monad reader it is shown how to use ScottyT to embed a Reader monad in the stack to access a static configuration (in that case, a connection pool).

我有一个类似的问题,但是更简单–或者至少我是这么认为的……

I have a similar question, but simpler – or at least I thought so…

我想将Reader添加到单个处理程序(即ActionT),而不是整个应用程序.

I want to add a Reader to a single handler (i.e. a ActionT), not the whole app.

我从上面的问题开始修改程序,但是我不知道如何将ActionT Text (ReaderT String IO)转换为处理程序所需的ActionT Text IO.在摸索并尝试使用类型化的孔之后,希望看到如何构造它,我现在必须放弃并寻求帮助.我真的觉得这应该很简单,但无法弄清楚该怎么做.

I started modifying the program from the question above, but I cannot figure out how to turn an ActionT Text (ReaderT String IO) into the ActionT Text IO the handler needs to be. After fumbling around and trying to use typed holes hoping to see how to construct this I have to give up for now and ask for help. I really feel this should be simple, but cannot figure out how to do this.

这是程序,突出显示我被卡住的行:

Here's the program, with the lines where I'm stuck highlighted:

{-# LANGUAGE OverloadedStrings #-}

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

type ActionD = ActionT Text (ReaderT String IO)

main :: IO ()
main = do
  scottyT 3000 id id app

-- Application
app ::  ScottyT Text IO ()
app = do
  get "/foo" $ do
    h <- handler              -- ?
    runReaderT h "foo"        -- ?
--get "/bar" $ do
--  h <- handler
--  runReaderT h "bar"

-- Route action handler
handler ::  ActionD ()
handler = do
  config <- lift ask
  html $ T.pack $ show config

推荐答案

如果要在单独的阅读器中运行每个操作,则根本不需要更复杂的Scotty.Trans界面.您可以以另一种方式构建monad堆栈,并在顶部放置ReaderT.

If you want to run each action in a separate reader, you don't need the more complex Scotty.Trans interface at all. You can just build you monad stack the other way around, with ReaderT on top.

import qualified Data.Text.Lazy as T
import           Control.Monad.Reader
import           Web.Scotty

type ActionD = ReaderT String ActionM

main :: IO ()
main = do
  scotty 3000 app

-- Application
app ::  ScottyM ()
app = do
  get "/foo" $ do
    runReaderT handler "foo"

-- Route action handler
handler ::  ActionD ()
handler = do
  config <- ask
  lift $ html $ T.pack $ show config

这篇关于适用于每个处理器读取器的Scotty Monad变压器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆