on 656f80a help sign in
50 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.Common.BaseUrl
16import Servant.Common.Req
17import Servant.Docs
18import Servant.Server
20-- | Endpoint for simple GET requests. The server doesn't receive any arguments
21-- and serves the contained type as JSON.
22data Get a
23 deriving Typeable
25instance ToJSON result => HasServer (Get result) where
26 type Server (Get result) = EitherT (Int, String) IO result
27 route Proxy action request respond
28 | null (pathInfo request) && requestMethod request == methodGet = do
29 e <- runEitherT action
30 respond . succeedWith $ case e of
31 Right output ->
32 responseLBS ok200 [("Content-Type", "application/json")] (encode output)
33 Left (status, message) ->
34 responseLBS (mkStatus status (cs message)) [] (cs message)
35 | null (pathInfo request) && requestMethod request /= methodGet =
36 respond $ failWith WrongMethod
37 | otherwise = respond $ failWith NotFound
39instance FromJSON result => HasClient (Get result) where
40 type Client (Get result) = BaseUrl -> EitherT String IO result
41 clientWithRoute Proxy req host =
42 performRequest methodGet req 200 host
44instance ToSample a => HasDocs (Get a) where
45 docsFor Proxy (endpoint, action) =
46 single endpoint' action'
48 where endpoint' = endpoint & method .~ DocGET
49 action' = action & response.respBody .~ toSample p
50 p = Proxy :: Proxy a