【问题标题】:Scotty api with mysql simple in haskell在haskell中使用mysql简单的Scotty api
【发布时间】:2017-12-12 13:04:38
【问题描述】:

我正在关注 this 教程,该教程使用 scotty 和持久性来创建一个简单的 API。

但是,我正在尝试使用 scotty 和 mysql 简单库创建一个简单的 api。

现在我卡在代码中的某一点上。

在下面的代码中,我无法将 getUser 函数转换为类型 "ActionT Error ConfigM",因为我的代码失败了。

谁能帮助我了解如何转换 getUser 函数以实现所需的类型签名?

代码

type Error = Text
type Action = ActionT Error ConfigM ()

config :: Config
config = Config
    { environment = Development 
     ,db1Conn = connect connectionInfo
    }

main :: IO ()
main = do
  runApplication config

runApplication :: Config -> IO ()
runApplication c = do
  o <- getOptions (environment c)
  let r m = runReaderT (runConfigM m) c
  scottyOptsT o r application

application :: ScottyT Error ConfigM ()
application = do
  e <- lift (asks environment)
  get "/user" getTasksA

getTasksA :: Action
getTasksA = do
    u <- getUser
    json u 

getUser :: IO User
getUser = do
  e <- asks environment
  conn <- db1Conn config 
  [user]<- query_ conn "select login as userId, email as userEmail from member limit 1"
  return user 

错误

• Couldn't match type ‘IO’ with ‘ActionT Error ConfigM’
      Expected type: ActionT Error ConfigM User
        Actual type: IO User
    • In a stmt of a 'do' block: u <- getUser
      In the expression:
        do { u <- getUser;
             json u }
      In an equation for ‘getTasksA’:
          getTasksA
            = do { u <- getUser;
                   json u }

【问题讨论】:

  • 如果你放弃IO User的签名,它可能会起作用。
  • 试过了。出现以下错误无法将类型“IO”与“ActionT Error ConfigM”匹配预期类型:ActionT Error ConfigM a0 实际类型:IO a0

标签: mysql haskell scotty


【解决方案1】:

您遗漏了大量代码(导入和编译指示以及User 的定义,请下次添加 - 请参阅MCVE

但现在你的问题:

我会将Action 类型更改为以下

type Action a = ActionT Error ConfigM a

那么getTasksA 具有以下类型签名

getTasksA :: Action ()
getTasksA = do
    u <- getUser
    json u 

(或者你也可以写成getTasksA = getUser &gt;&gt;= json

getUser

getUser :: Action User
getUser = do
  e <- asks environment
  conn <- db1Conn config 
  [user] <- liftIO $ query_ conn "select login as userId, ..."
  return user

几点说明

  • [user] &lt;- liftIO $ query .. 是个坏主意——如果找不到用户,这会使你的应用程序崩溃——尝试编写总函数和模式匹配。最好返回Maybe User

    getUser :: Action (Maybe User)
    getUser = do
      e <- asks environment
      conn <- db1Conn config 
      fmap listToMaybe . liftIO $ query_ conn "select login as userId, ..."
    
  • 1234563 /p>
  • ask 多次为 environment 但后来不要使用它。使用-Wall 甚至-Werror 进行编译以获得警告,甚至提升警告以编译错误(这对于生产设置来说是个好主意。

【讨论】:

  • 另外,我实际上想使用 Persistent 库,但是 Persistent 会动态创建我的数据类型。在这种情况下,就像 User 数据类型一样。然后我将不得不在我想要使用 User 数据类型的代码中的任何地方导入该文件,这将在我的整个代码库中创建 Persistent 的依赖关系。因此,我没有使用它。
猜你喜欢
  • 1970-01-01
  • 2015-06-11
  • 1970-01-01
  • 2018-11-15
  • 1970-01-01
  • 2015-04-14
  • 2012-04-24
  • 2013-07-18
  • 2014-06-25
相关资源
最近更新 更多