on 85acead help sign in
55 lines 1.8 kB history raw
1{-# LANGUAGE TypeFamilies #-}
2{-# LANGUAGE OverloadedStrings #-}
3{-# LANGUAGE ScopedTypeVariables #-}
4{-# LANGUAGE DeriveDataTypeable #-}
5module Servant.API.Post where
7import Control.Monad.Trans.Either
8import Data.Aeson
9import Data.Proxy
10import Data.String.Conversions
11import Data.Typeable
12import Network.HTTP.Types
13import Network.Wai
14import Servant.Client
15import Servant.Docs
16import Servant.Server
17import Servant.Utils.Client
19-- | Endpoint for POST requests. The type variable represents the type of the
20-- response body (not the request body, use 'Servant.API.RQBody.RQBody' for
21-- that).
22data Post a
23 deriving Typeable
25instance ToJSON a => HasServer (Post a) where
26 type Server (Post a) = EitherT (Int, String) IO a
28 route Proxy action request respond
29 | null (pathInfo request) && requestMethod request == methodPost = do
30 e <- runEitherT action
31 respond . succeedWith $ case e of
32 Right out ->
33 responseLBS status201 [("Content-Type", "application/json")] (encode out)
34 Left (status, message) ->
35 responseLBS (mkStatus status (cs message)) [] (cs message)
36 | null (pathInfo request) && requestMethod request /= methodPost =
37 respond $ failWith WrongMethod
38 | otherwise = respond $ failWith NotFound
40instance FromJSON a => HasClient (Post a) where
41 type Client (Post a) = BaseUrl -> EitherT String IO a
43 clientWithRoute Proxy req uri =
44 performRequest methodPost req 201 uri
46instance ToSample a => HasDocs (Post a) where
47 docsFor Proxy (endpoint, action) =
48 single endpoint' action'
50 where endpoint' = endpoint & method .~ DocPOST
52 action' = action & response.respBody .~ toSample p
53 & response.respStatus .~ 201
55 p = Proxy :: Proxy a