on 1dd253d help sign in
servant/src/Servant/API/Delete.hs
71 lines 2.4 kB history raw
1{-# LANGUAGE TypeFamilies #-}
2{-# LANGUAGE OverloadedStrings #-}
3{-# LANGUAGE ScopedTypeVariables #-}
4{-# LANGUAGE DeriveDataTypeable #-}
5module Servant.API.Delete where
7import Control.Monad.Trans.Either
8import Data.Proxy
9import Data.String.Conversions
10import Data.Typeable
11import Network.HTTP.Types
12import Network.Wai
13import Servant.Client
14import Servant.Common.BaseUrl
15import Servant.Common.Req
16import Servant.Docs
17import Servant.Server
19-- | Combinator for DELETE requests.
20--
21-- Example:
22--
23-- > -- DELETE /books/:isbn
24-- > type MyApi = "books" :> Capture "isbn" Text :> Delete
25data Delete
26 deriving Typeable
28-- | If you have a 'Delete' endpoint in your API,
29-- the handler for this endpoint is meant to delete
30-- a resource.
31--
32-- The code of the handler will, just like
33-- for 'Servant.API.Get.Get', 'Servant.API.Post.Post' and
34-- 'Servant.API.Put.Put', run in @EitherT (Int, String) IO ()@.
35-- The 'Int' represents the status code and the 'String' a message
36-- to be returned. You can use 'Control.Monad.Trans.Either.left' to
37-- painlessly error out if the conditions for a successful deletion
38-- are not met.
39instance HasServer Delete where
40 type Server Delete = EitherT (Int, String) IO ()
42 route Proxy action request respond
43 | null (pathInfo request) && requestMethod request == methodDelete = do
44 e <- runEitherT action
45 respond $ succeedWith $ case e of
46 Right () ->
47 responseLBS status204 [] ""
48 Left (status, message) ->
49 responseLBS (mkStatus status (cs message)) [] (cs message)
50 | null (pathInfo request) && requestMethod request /= methodDelete =
51 respond $ failWith WrongMethod
52 | otherwise = respond $ failWith NotFound
54-- | If you have a 'Delete' endpoint in your API, the client
55-- side querying function that is created when calling 'client'
56-- will just require an argument that specifies the scheme, host
57-- and port to send the request to.
58instance HasClient Delete where
59 type Client Delete = BaseUrl -> EitherT String IO ()
61 clientWithRoute Proxy req host =
62 performRequestJSON methodDelete req 204 host
64instance HasDocs Delete where
65 docsFor Proxy (endpoint, action) =
66 single endpoint' action'
68 where endpoint' = endpoint & method .~ DocDELETE
70 action' = action & response.respBody .~ Nothing
71 & response.respStatus .~ 204