StateT monad 在 purescript-express 中的 Handler 内部

huangapple go评论57阅读模式
英文:

StateT monad inside Handler in purescript-express

问题

Handlerpost(任何HTTP方法)函数的内部,我想要在StateT单子中保留一些数据,但问题是我无法在Handler内部使用State...

newtype HandlerM a = HandlerM (Request -> Response -> Effect Unit -> Aff a)

type Handler = HandlerM Unit

HTTP方法的类型如下,

post :: forall r. RoutePattern r => r -> Handler -> App

我想要做类似这样的事情,

post "/some/api" $ do 
     S.modify (\s -> s { count = s.count + 1}) -- 根据响应修改状态
     -- 处理请求

附注:我可以使用ref,但是否有办法在Handler内部使用StateT...

英文:

I want to persist some data in StateT monad,

Within Handler of the post(any http method) function I want to modify the data stored in state... but the issue is I can't use State inside Handler...

newtype HandlerM a =  HandlerM (Request -> Response -> Effect Unit -> Aff a)

type Handler = HandlerM Unit

and type of http methods are as follows,

post :: forall r. RoutePattern r => r -> Handler -> App

I want to do something like,

post "/some/api" $ do 
     S.modify (\s -> s { count = s.+ 1}} ---- modify state with respect to response 
     --- handle request

ps: I can use ref but is there any way I can use StateT inside Handler...

答案1

得分: 1

不,你需要使用 Ref 来实现这一点,State 在这种情况下不起作用。

如果你可以通过引用传递它,每个处理的请求都将在自己的 State 中运行,并在每次开始时重新使用初始值。

英文:

No, you'd have to use a Ref for this - State doesn't work in situations like this.

If you could plumb it through, what would happen is each request being processed would operate in its own State, starting over with the initial value each time.

huangapple
  • 本文由 发表于 2023年2月27日 17:20:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75578633.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定