我试图自己学习HASKELL,我发现了这个页面https://www.parsonsmatt.org/2015/05/02/scotty_and_persistent.html,我试图使用代码,但我得到了一个错误:
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Products
name Text
description Text
price Int
deriving Show
|]
main :: IO ()
main = scotty 3000 $ do
Web.Scotty.middleware logStdoutDev
inAppDb $ do
doDbStuff
Web.Scotty.get "/api/products" $ json [(0::Int)..10]
inAppDb = liftIO . dbFunction
dbFunction query = runStderrLoggingT $
withPostgresqlPool connStr 10 $
\pool -> liftIO $ runSqlPersistMPool query pool
doDbStuff = do
res :: [Entity Products] <- selectList [] [LimitTo 1]
liftIO $ print res
字符串
误差
➜ my-project stack run
my-project> build (lib + exe)
Preprocessing library for my-project-0.1.0.0..
Building library for my-project-0.1.0.0..
ld: warning: -single_module is obsolete
Preprocessing executable 'my-project-exe' for my-project-0.1.0.0..
Building executable 'my-project-exe' for my-project-0.1.0.0..
[1 of 3] Compiling Main [Source file changed]
/Users/home/my-project/app/Main.hs:176:11: error:
• No instance for (Control.Monad.IO.Class.MonadIO
(Web.Scotty.Internal.Types.ScottyT
Data.Text.Internal.Lazy.Text IO))
arising from a use of ‘liftIO’
• In the first argument of ‘(.)’, namely ‘liftIO’
In the expression: liftIO . dbFunction
In an equation for ‘inAppDb’: inAppDb = liftIO . dbFunction
|
176 | inAppDb = liftIO . dbFunction
| ^^^^^^
Error: [S-7282]
Stack failed to execute the build plan.
While executing the build plan, Stack encountered the error:
[S-7011]
While building package my-project-0.1.0.0 (scroll up to its section to see the error) using:
/Users/home/.stack/setup-exe-cache/aarch64-osx/Cabal-simple_6HauvNHV_3.8.1.0_ghc-9.4.7 --verbose=1 --builddir=.stack-work/dist/aarch64-osx/ghc-9.4.7 build lib:my-project exe:my-project-exe --ghc-options " -fdiagnostics-color=always"
Process exited with code: ExitFailure 1
型
我不知道为什么会出现错误:liftIO .
你对此有什么想法吗?
Thanks in advance
Aron
2条答案
按热度按时间jdzmm42g1#
根据评论,Scotty从0.10版本开始重新设计,使
ScottyM
(和ScottyT
)成为一个“仅配置”的monad,它声明了Web服务器的中间件和路由,但本身不能执行I/O。因此,博客作者试图使用
inAppDb
将任何数据库设置或其他I/O移动到Scotty应用程序中都不会工作。相反,在调用scotty
之前删除inAppDb
定义并将该设置移动到main
中。对于您的特定代码示例,它看起来像这样:字符串
就博客文章的其余部分而言,看起来作者在第2部分放弃了整个
inAppDb
,inHandlerDb
调用应该都能正常工作。它们在ActionM
monad中运行,该monad支持通过liftIO
进行I/O操作,因此下面的示例应该进行类型检查:型
l5tcr1uw2#
我终于完成了我的代码。我现在有一个Haskell的例子,使用Scotty,Persistent(Postgresql)和一个返回JSON数据的GET方法。
下面是完整的代码:
字符串
我还分享了我使用过的依赖项列表及其各自的版本:
型
这是我的第一个代码,所以我会继续改进它,以便更多地了解Haskell(欢迎所有提示和技巧!)。
最后,我想感谢大家抽出时间回答我最初的问题。