servant/src/Servant/API/JsonBody.hs

52 lines
1.4 KiB
Haskell
Raw Normal View History

{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
2014-10-28 15:29:07 +01:00
module Servant.API.JsonBody where
import Control.Applicative
import Data.Aeson
import Data.Proxy
import Network.Wai
import Servant.API.Sub
import Servant.Client
import Servant.Docs
import Servant.Server
-- * Request Body support
2014-10-28 15:29:07 +01:00
data JsonBody a
instance (FromJSON a, HasServer sublayout)
2014-10-28 15:29:07 +01:00
=> HasServer (JsonBody a :> sublayout) where
2014-10-28 15:29:07 +01:00
type Server (JsonBody a :> sublayout) =
a -> Server sublayout
route Proxy subserver request respond = do
mrqbody <- decode' <$> lazyRequestBody request
case mrqbody of
Nothing -> respond $ failWith NotFound
Just v -> route (Proxy :: Proxy sublayout) (subserver v) request respond
instance (ToJSON a, HasClient sublayout)
2014-10-28 15:29:07 +01:00
=> HasClient (JsonBody a :> sublayout) where
2014-10-28 15:29:07 +01:00
type Client (JsonBody a :> sublayout) =
a -> Client sublayout
clientWithRoute Proxy req body =
clientWithRoute (Proxy :: Proxy sublayout) $
setRQBody (encode body) req
instance (ToSample a, HasDocs sublayout)
2014-10-28 15:29:07 +01:00
=> HasDocs (JsonBody a :> sublayout) where
docsFor Proxy (endpoint, action) =
docsFor sublayoutP (endpoint, action')
where sublayoutP = Proxy :: Proxy sublayout
action' = action & rqbody .~ toSample p
p = Proxy :: Proxy a