on 0e9d075 help sign in
49 lines 1.7 kB history raw
1{-# LANGUAGE TypeFamilies #-}
2{-# LANGUAGE OverloadedStrings #-}
3{-# LANGUAGE ScopedTypeVariables #-}
4{-# LANGUAGE DeriveDataTypeable #-}
5module Servant.API.Get 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 simple GET requests. The server doesn't receive any arguments
20-- and serves the contained type as JSON.
21data Get a
22 deriving Typeable
24instance ToJSON result => HasServer (Get result) where
25 type Server (Get result) = EitherT (Int, String) IO result
26 route Proxy action request respond
27 | null (pathInfo request) && requestMethod request == methodGet = do
28 e <- runEitherT action
29 respond . succeedWith $ case e of
30 Right output ->
31 responseLBS ok200 [("Content-Type", "application/json")] (encode output)
32 Left (status, message) ->
33 responseLBS (mkStatus status (cs message)) [] (cs message)
34 | null (pathInfo request) && requestMethod request /= methodGet =
35 respond $ failWith WrongMethod
36 | otherwise = respond $ failWith NotFound
38instance FromJSON result => HasClient (Get result) where
39 type Client (Get result) = BaseUrl -> EitherT String IO result
40 clientWithRoute Proxy req host =
41 performRequest methodGet req 200 host
43instance ToSample a => HasDocs (Get a) where
44 docsFor Proxy (endpoint, action) =
45 single endpoint' action'
47 where endpoint' = endpoint & method .~ DocGET
48 action' = action & response.respBody .~ toSample p
49 p = Proxy :: Proxy a