我尝试使用servant库创建到Web API的客户端绑定。 我希望能够发送任何JSON对象。
import Control.Monad.Trans.Except (ExceptT, runExceptT)
import Data.Proxy
import Network.HTTP.Client (Manager)
import Servant.API
import Servant.Client
import Data.Aeson
-- | This methods accepts any instance of 'ToJSON'
-- I would like to have only this method exported from the module
send :: ToJSON a => a -> Manager -> IO (Either ServantError Result)
send x manager = runExceptT $ send_ x manager baseUrl
type MyAPI a = "acceptAnyJson"
:> ReqBody '[JSON] a
:> Post '[JSON] Result
api :: ToJSON a => Proxy (MyAPI a)
api = Proxy
send_ :: ToJSON a => a -> Manager -> BaseUrl -> ExceptT ServantError IO Result
send_ = client api
现在当我尝试编译它时,我有错误消息:
Couldn't match type ‘a0’ with ‘a’
because type variable ‘a’ would escape its scope
This (rigid, skolem) type variable is bound by
the inferred type for ‘send_’:
...
如何将MyAPI
,client
和Proxy
参数化以接受类型变量?
答案 0 :(得分:1)
您需要将api
的类型与您要发送的内容的类型联系起来:
{-# LANGUAGE ScopedTypeVariables #-}
send_ :: forall a. (FromJSON a) => a -> Manager -> BaseUrl -> ExceptT ServantError IO Result
send_ = client (api :: Proxy (MyAPI a))
或者为什么在这一点上甚至打扰api
:
send_ = client (Proxy :: Proxy (MyAPI a))