Rey*_*och 4 database authentication haskell pool servant
我正在使用自定义monad(带阅读器)轻松地将数据库(如DB池)传递给我的处理程序(在使用自定义monad之前,我曾将连接作为fn参数传递).
这就是我定义自定义monad的方法:
newtype Controller a = Controller
{ runController :: ReaderT ServerEnvironment Handler a
} deriving ( Functor, Applicative, Monad, MonadReader ServerEnvironment,
MonadError ServantErr, MonadIO )
Run Code Online (Sandbox Code Playgroud)
这ServerEnvironment只是我用来携带数据的自定义数据类型.
问题是,对于我,AuthHandler我必须具体使用以下功能:
r -> Handler usr
Run Code Online (Sandbox Code Playgroud)
作为身份验证处理程序,我不能使用我的自定义处理程序,它将是:
r -> Controller usr
Run Code Online (Sandbox Code Playgroud)
而且我也无法传递我,ConnectionPool因为签名不能是:
ConnPool -> r -> Handler usr
Run Code Online (Sandbox Code Playgroud)
那么,如何在不使用全局IO状态的情况下将额外数据传递给servant中的身份验证处理程序?
将AuthHandler你放入上下文没有在顶层进行定义!通常,您需要这样做,main以便您可以访问您创建的数据库连接等:
type API =
... :<|> (AuthProtect "myProtection" :> ...) :<|> ...
type instance AuthServerData (AuthProtect "myProtection") = User
server :: ServerEnvironment -> Server API
server env = ...
setupEnv :: IO ServerEnvironment
setupEnv = ..
-- This is essentially a 'Controller'.
authenticate :: ServerEnvironment -> Handler User
authenticate conn = ...
main :: IO ()
main = do
env <- setupEnv
-- Now, because we have access to the env, we can turn our
-- 'authenticate' into the right type before putting it
-- in the context
let ctx = authenticate env :. EmptyContext
run 8080 $ serveWithContext myAPI (server conn) ctx
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
412 次 |
| 最近记录: |