Sto utilizzando la libreria servant
per la mia API JSON. Ho bisogno di aiuto per far funzionare uno stack monad ServerT MyAPI (ReaderT a IO)
.Utilizzo di servant con ReaderT IO a
Ecco un esempio di utilizzo ReaderT
, ma senza integrandola con servo:
-- this code works
type TestAPI =
"a" :> Get '[JSON] String
:<|> "b" :> Get '[JSON] String
test2 :: EitherT ServantErr IO String
test2 = return "asdf"
testServer :: Int -> Server TestAPI
testServer code = test :<|> test2
where
test :: EitherT ServantErr IO String
test = liftIO $ runReaderT (giveMeAMessage) code
-- this is contrived. In my real application I want to use a Reader for the database connection.
giveMeAMessage :: ReaderT Int IO String
giveMeAMessage = do
code <- ask
name <- liftIO $ getProgName
return $ show code <> name
Così, ora vorrei farlo funzionare con SERVERT, seguendo l'esempio di this article.
-- this code doesn't compile
testServerT :: ServerT TestAPI (ReaderT Int IO)
testServerT = test :<|> test
where
test :: EitherT ServantErr (ReaderT Int IO) String
test = lift $ giveMeAMessage
testServer' :: Int -> Server TestAPI
testServer' code = enter (Nat $ liftIO . (`runReaderT` code)) testServerT
ottengo il seguente errore:
server/Serials/Route/Test.hs:43:15:
Couldn't match type ‘EitherT ServantErr (ReaderT Int IO) String’
with ‘ReaderT Int IO [Char]’
Expected type: ServerT TestAPI (ReaderT Int IO)
Actual type: EitherT ServantErr (ReaderT Int IO) String
:<|> EitherT ServantErr (ReaderT Int IO) String
In the expression: test :<|> test
In an equation for ‘testServerT’:
testServerT
= test :<|> test
where
test :: EitherT ServantErr (ReaderT Int IO) String
test = lift $ giveMeAMessage
Failed, modules loaded: none.
Come posso eliminare l'errore?
Domanda successiva: Capisco i trasformatori monad in generale, ma sono perso. Quali argomenti o collegamenti dovrei studiare per conoscere abbastanza per rispondere alla mia domanda?
Grazie pingu. Non avevo capito che l'EitherT ServantErr un tipo nella mia funzione server era facoltativo, perché ho ancora bisogno di gestire gli errori in qualche modo. Pensavo che dovevo finire con quello. Non mi rendevo conto che potevo farlo nella mia funzione di corsa. Vedi la mia risposta qui sotto. –