簡體   English   中英

GET Route ActionCtxT錯誤內的Haskell Spock IO錯誤

[英]Haskell Spock IO within GET Route ActionCtxT Error

我嘗試在Web應用程序( Spock Web服務器)的路由定義中返回uuid。

路線很容易定義

get("PATH") $ do
 text "Hello World"

現在,我嘗試通過返回UUID nextRandomData.UUID.V1模塊。 該函數返回IO(Maybe UUID)值。

所以我想,因為我在IO中並與另一個IO一起工作,所以我必須使用<-綁定值,就像這樣:

get ("id") $ do
    uuid<-nextUUID
    json . pack $ show $ uuid

但是編譯器拒絕:

Couldn't match type ‘ActionCtxT ctx0 m0’ with ‘IO’
      Expected type: IO b0
        Actual type: ActionCtxT ctx0 m0 b0
    • In a stmt of a 'do' block: json . pack $ show $ uuid
      In the second argument of ‘($)’, namely
        ‘do { uuid <- nextUUID;
              json . pack $ show $ uuid }’

為什么會拋出該錯誤? 我可以使用簡單的打印示例輕松創建uuid,但是在Spock中,我不了解ActionCtxT的功能以及為什么不能在其中執行uuid IO。

所以我想,因為我在IO中並與另一個IO合作

這就是問題所在,當您在Spock中進行路由時,您不在IO中。 錯誤消息會告訴您您真正處於哪個上下文中: ActionCtxT ctx0 m0 根據文檔 ,這是一個捆綁效果和狀態的monad變壓器堆棧

您可以使用liftIO將IO計算“提升”為正確的類型。

get ("id") $ do
    uuid <- liftIO nextUUID
    json . pack $ show $ uuid

根據Libbys的有用答案,我剛剛添加了Nothing of Maybe UUID 這里是完整的程序:

{-# LANGUAGE OverloadedStrings #-}


module Main where

import Web.Spock hiding (head)
import Web.Spock.Config

import Data.UUID.V1
import Data.Pool
import Control.Monad.IO.Class
import Database.PostgreSQL.Simple
import Data.Aeson (Value(Null))

import qualified Network.HTTP.Types.Status as Http

type AppAction a = SpockActionCtx () Connection AppSession AppState a
data AppState = EmptyState
data AppSession = EmptySession


main :: IO ()
main =
  do pool<-createPool (connect (ConnectInfo "localhost" 5432 "" "" "envelopes") ) close 1 10 10
     spockCfg <- defaultSpockCfg EmptySession (PCPool pool) EmptyState
     runSpock 8080 (spock spockCfg app)

app :: SpockM Connection AppSession AppState ()
app = do 
    get ("json/id") $ do
      uuid<-liftIO nextUUID
      case uuid of
        Nothing -> do 
          setStatus Http.status500
          json Null
        Just x  -> json $ show x

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM